Solution to the failure of RadioButton setting setChecked(true) in android

Phenomenon

The code is pasted at the bottom. OnCheckedChangeListener has received the listener, and it is checked = true, but the status of RadioButton is unchecked.
Finally, it was found that there was a problem with android:drawableStart="@drawable/sel_detail_table_grid".

verify

Remove these two lines of code and observe the status of the original icon, which is a normal replacement.

android:button="@null"
android:drawableStart="@drawable/sel_detail_table_grid"

question

When doing projects, you always need to customize the RadioButton style. Here I use android:button="@null" to remove the original button, and then add a custom icon. It is clear that the selected state of the sel tag is set, and the adaptive icon is normal when clicked, but the default selection when entering the setting for the first time only triggers an event, and does not automatically change the icon.

Solution

android:drawableStart="@drawable/sel_detail_table_grid"
替换成
android:background="@drawable/sel_detail_table_grid"

root cause

have no idea

original code

tableRadioGroup.setOnCheckedChangeListener((group, checkedId) -> showTableFragment(checkedId));
tableRadioGroup.check(R.id.grid_rb);
  <RadioGroup
                android:id="@+id/table_rg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end|center_vertical"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/grid_rb"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="16dp"
                    android:button="@null"
                    android:drawableStart="@drawable/sel_detail_table_grid" />

                <RadioButton
                    android:id="@+id/list_rb"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:button="@null"
                    android:drawableStart="@drawable/sel_detail_table_list" />
            </RadioGroup>

sel_detail_table_grid.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_detail_table_grid" android:state_checked="true" />
    <item android:drawable="@drawable/ic_detail_table_grid_" android:state_checked="false" />
</selector>

Digression: The clearCheck method of RadioGroup can set the RadioButton to the initial unselected state.

Guess you like

Origin blog.csdn.net/changhuzichangchang/article/details/109113446