2 回答

TA貢獻1818條經(jīng)驗 獲得超11個贊
您必須將選定的單選按鈕 ID 保留到您的模型中。
1> 在你的模型中選擇 selectedId。
class Model{
int selctedId;
// getter setter
}
2> 將此 ID 附加到您的無線電組。
@Override
public void onBindViewHolder(final CoachListViewHolder holder, final int position) {
Model model = list.get(position);
holder.radioGroup.check(model.getSelectedId);
holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
model.setSelectedId(checkedId);
}
});
在這個解決方案中,我們在模型中保存了選定的 id,我們將此字段附加到無線電組中 radioGroup.check(model.getSelectedId);
原因
當(dāng)您不保留所選值時,它會在用戶滾動位置時被回收。
我也發(fā)現(xiàn)了一個相關(guān)的問題。
久經(jīng)考驗的解決方案
您正在使用數(shù)據(jù)綁定,因此上述解決方案可以更短。使用雙向綁定來保存選定的 id。
項目.java
public class Item extends BaseObservable{
private int selectedId;
public int getSelectedId() {
return selectedId;
}
public void setSelectedId(int selectedId) {
this.selectedId = selectedId;
}
}
行列表.xml
<data>
<variable
name="item"
type="com.innovanathinklabs.sample.ui2.Item"/>
</data>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:background="@color/colorPrimary"
android:checkedButton="@={item.selectedId}"
>
<android.support.v7.widget.AppCompatRadioButton
android:id="@+id/rbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="male"/>
<android.support.v7.widget.AppCompatRadioButton
android:id="@+id/rbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="female"/>
</RadioGroup>
現(xiàn)在,當(dāng)您需要獲取所選項目時。然后這樣做。
if(list.get(1).getSelectedId() == R.id.rbMale){
// male is selected
}
else if (list.get(1).getSelectedId() == R.id.rbMale){
// female is selcted
}
同時從 Radio 組和 Radio 按鈕中刪除任何其他不必要的邏輯。
數(shù)據(jù)綁定魔法是
此代碼轉(zhuǎn)換為 android:checkedButton="@={item.selectedId}"

TA貢獻2021條經(jīng)驗 獲得超8個贊
添加private int isFirstQuestionChecked = false到您的模型并在您選擇此項時對其進行更改RadioButton。在您的適配器中顯示正確的值RadioButton
if (element.isFirstQuestionChecked == true) {
selectRadioButton()
} else {
deselectRadioButton() // it's important!
}
添加回答
舉報