我们正在开发一个项目,其中有一个自定义列表视图,每个列表项中都有一个无线电组。其中的单选按钮是动态生成的。问题是滚动时所选单选按钮的状态将被取消选择。以下是我们尝试过的代码:
适配器getView()方法:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/single_question_name"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/single_radiogroup"
android:orientation="vertical"
>
</RadioGroup>
</LinearLayout>
编辑: 这是single_choice_layout.xml文件:
{{1}}
答案 0 :(得分:0)
如果我正确理解您的代码。您还需要实现此方法。
check(int id) 将选择设置为标识符在参数中传递的单选按钮。
答案 1 :(得分:0)
试试这段代码
public View getView(final int position, View convertView, ViewGroup parent) {
//give the corrct class name
QuestionObj rowObject = question_list_array.get(position);
option_list = question_list_array.get(position).option_list;
number_of_options = option_list.size();
v_single = convertView;
SingleHolder sh;
if (v_single == null) {
v_single = inflater.inflate(R.layout.single_choice_layout, null);
sh = new SingleHolder();
sh.single_question_name = (TextView) v_single.findViewById(R.id.single_question_name);
sh.single_radiogroup = (RadioGroup) v_single.findViewById(R.id.single_radiogroup);
v_single.setTag(sh);
} else {
sh = (SingleHolder) v_single.getTag();
}
sh.single_question_name.setText(rowObject.getQuestion_name());
sh.single_radiogroup.clearCheck();
sh.single_radiogroup.removeAllViews();
for (int j = 0; j < number_of_options; j++) {
RadioButton rb = new RadioButton(context);
rb.setId(Integer.parseInt(option_list.get(j).getOption_id()));
rb.setText(option_list.get(j).getOption_name());
sh.single_radiogroup.addView(rb);
}
if (rowObject.getSelectedId() != 0) {
RadioButton radioButton = (RadioButton) sh.single_radiogroup.findViewById(rowObject.getSelectedId());
if (radioButton != null)
radioButton.setChecked(true);
}
sh.single_radiogroup.setTag(rowObject);
sh.single_radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
QuestionObj rowObject = (QuestionObj) group.getTag();
rowObject.setSelectedId(checkedId);
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
rowObject.setAnswer(radioButton.getText());
}
});
v_final = v_single;
return v_final;
}
private class SingleHolder {
TextView single_question_name;
RadioGroup single_radiogroup;
}
class QuestionObj {
private int selectedId;
public int getSelectedId() {
return selectedId;
}
public void setSelectedId(int selectedId) {
this.selectedId = selectedId;
}
//put this is in those
//other fieldds like questionname, question id,
}