美文网首页
radiobutton 点击无法切换

radiobutton 点击无法切换

作者: 爱言语论 | 来源:发表于2018-12-20 16:38 被阅读35次

就像平时写的代码一样radiogroup 里面放两个radiobutton,代码如下

       <RadioGroup
        android:id="@+id/rb_over_rest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="@dimen/dp_4"
        app:layout_constraintTop_toBottomOf="@+id/line1">

        <RadioButton
            style="@style/MyRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:tag="2"
            android:text="加班(+)"
            android:textColor="@drawable/select_check_yellow" />

        <RadioButton
            style="@style/MyRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:tag="3"
            android:text="请假(—)"
            android:textColor="@drawable/select_check_yellow" />

    </RadioGroup>

颜色

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/yellow" android:state_checked="true" />
<item android:color="#ff979797" android:state_checked="false" />
<item android:color="#ff979797"></item>
</selector>

但是实际ui点击却只生效一次,再次点击却不生效,最后和以前代码一点点比对,一点点测试才发现是因为RadioButton没有定义id,加上id 就好了。

翻开RadioGroup 源码 查看check方法
还有这行代码

 int value = attributes.getResourceId(R.styleable.RadioGroup_checkedButton, View.NO_ID);
 if (value != View.NO_ID) {
            mCheckedId = value;
            mInitialCheckedId = value;
        }
public void check(@IdRes int id) {
        // don't even bother
        if (id != -1 && (id == mCheckedId)) {
            return;
        }

        if (mCheckedId != -1) {
            setCheckedStateForView(mCheckedId, false);
        }

        if (id != -1) {
            setCheckedStateForView(id, true);
        }

        setCheckedId(id);
    }

可以知道底层RadioGroup 是获取了点击的radiobutton 的id的,所以才会出现我这样的情况。

相关文章

网友评论

      本文标题:radiobutton 点击无法切换

      本文链接:https://www.haomeiwen.com/subject/eeaykqtx.html