首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >安卓RadioGroup在双向DataBinding中检查RadioButton索引(位置)

安卓RadioGroup在双向DataBinding中检查RadioButton索引(位置)
EN

Stack Overflow用户
提问于 2020-11-19 02:01:22
回答 1查看 101关注 0票数 1

以下是我目前的解决方案:

代码语言:javascript
运行
复制
<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:onCheckedChanged="@{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.findViewById(buttonId)))}"
    android:orientation="horizontal">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:checked="@{student.genderIndex == 0}"
        android:text="Male" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@{student.genderIndex == 1}"
        android:text="Female" />

</RadioGroup>

这很好用,但我想知道是否有更好的方法来做到这一点。然后我发现RadioGroupandroid:checkedButton (来自Official Documentation)有一个内置的双向属性,但是它是id而不是我想要的索引:

代码语言:javascript
运行
复制
public static final int checkedButton

The id of the child radio button that should be checked by default within this radio group.

May be an integer value, such as "100".

Constant Value: 16843080 (0x01010148)

我仍然尝试(使我的绑定表达式更短),但不起作用:

代码语言:javascript
运行
复制
android:onCheckedChanged="@{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.checkedButton))}"

"Could not find accessor android.widget.RadioGroup.checkedButton"

EN

Stack Overflow用户

发布于 2021-10-11 12:56:42

像这样添加onCheckedChanged

代码语言:javascript
运行
复制
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onCheckedChanged="@{vm.onSplitTypeChanged}">
    
    <RadioButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/email" />
    
    <RadioButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/sms" />
</RadioGroup>

然后在视图模型中实现onSplitTypeChanged,如下所示

代码语言:javascript
运行
复制
fun onSplitTypeChanged(radioGroup: RadioGroup?, id: Int) {
        val checked = radioGroup?.findViewById<RadioButton>(id)
        val index = radioGroup?.indexOfChild(checked)
    }
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64898737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档