我有一个带有文本和 3 个单选按钮的 ListView 。如果我选择任何单选按钮,并滚动列表,单选按钮将被取消选中。我正在维护选择单选按钮的项目的 ID,并在适配器 Getview 中设置要选择的所需单选按钮。在调试时,它正在执行语句 setChecked(true)
但单选按钮仍未选中。我尝试了 setSelected(true)
并通过 radio 组 ((RadioButton)holder.rg.getChildAt(2)).setChecked(true);
进行设置,但似乎没有任何效果.
XML:
<TextView
android:id="@+id/refill_product_name"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="@string/hello_world"
android:textColor="@android:color/black"
android:textStyle="normal"
android:textSize="@dimen/item_sub_heading"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginStart="@dimen/activity_horizontal_margin"/>
<RadioGroup
android:id="@+id/refill_product_rg"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<RadioButton
android:id="@+id/refill_product_regular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/regular"
android:textColor="@android:color/black"
android:textStyle="bold"
android:buttonTint="@color/primary"/>
<RadioButton
android:id="@+id/refill_product_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/small"
android:textColor="@android:color/black"
android:textStyle="bold"
android:layout_marginLeft="@dimen/radio_btn_margin"
android:buttonTint="@color/primary"/>
<RadioButton
android:id="@+id/refill_product_extra_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/extra_small"
android:textColor="@android:color/black"
android:textStyle="bold"
android:layout_marginLeft="@dimen/radio_btn_margin"
android:buttonTint="@color/primary"/>
</RadioGroup>
适配器代码:
private class ViewHolder {
TextView productName;
RadioButton regularBtn, smallBtn, extraSmallBtn;
RadioGroup rg;
}
适配器中的GetView方法
holder.rg.clearCheck();
if (mAppSession.getSelRefillProducts() != null) {
for (RefillProduct pr : mAppSession.getSelRefillProducts()) {
if (pr.getProductId() == rf.getProductId()) {
if (pr.getSize().equals("R")) {
((RadioButton)holder.rg.getChildAt(0)).setChecked(true);
} else if (pr.getSize().equals("S")) {
holder.smallBtn.setSelected(true);
} else if (pr.getSize().equals("XS")) {
((RadioButton)holder.rg.getChildAt(2)).setChecked(true);
}
}
}
}
我不确定我是否遗漏了什么,但是 setChecked 或 setSelected 不起作用。请指教。
最佳答案
试试这个,在将单选按钮设置为选中之前,清除单选组中的所有选中:
yourRadioGroup.clearCheck();
yourRadioButton.setChecked(true);
关于android - 单选按钮 setChecked/setSelected 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38264051/