【发布时间】:2016-11-10 20:51:08
【问题描述】:
我有一个带有文本和 3 单选按钮的列表视图。如果我选择任何单选按钮,并滚动列表,单选按钮将被取消选中。我正在维护选择单选按钮的项目的 ID,并在适配器 Getview 中设置要选择的所需单选按钮。在调试时,它正在执行语句setChecked(true),但单选按钮仍未选中。我尝试了setSelected(true) 并通过无线电组((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 不起作用。请指教。
【问题讨论】:
-
setSelected完全是else。甚至不要指望它会起作用。现在让我来看看并尝试推断为什么setChecked不起作用。尝试将android:clickable="true"添加到单选按钮中,看看是否会有所不同。 -
按照建议尝试。但正如预期的那样,没有区别。实际上,这似乎不是回收视图问题,因为选定的单选按钮未被选中,并且列表项都没有选中单选按钮。
-
您不能使用单个
holder对象在单个方法中遍历每个项目的单选按钮。(RadioButton)holder.rg.getChildAt(0)).setChecked(true);将只检查一个单选按钮而不是整个列表中的每个单选按钮。 -
我相信适配器中的 GetView 方法会为列表中的每个项目调用,因此我们可以为列表视图中的每个项目设置子项目的状态。在调试期间它正在执行语句 setChecked(true) 但仍然未选中单选按钮。
-
@JankiGadhiya 的评论对我有用!
标签: android android-radiogroup