【发布时间】:2016-01-14 15:10:55
【问题描述】:
我们正在开发一个项目,其中有一个自定义列表视图,每个列表项中都有一个单选组。其中的单选按钮是动态生成的。问题是在滚动时选中的单选按钮的状态变为取消选中。以下是我们尝试过的代码:
适配器getView()方法:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
option_list = question_list_array.get(position).option_list;
number_of_options = option_list.size();
v_single=convertView;
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_radiogroup.clearCheck();
sh.single_radiogroup.removeAllViews();
sh.single_question_name.setText(question_list_array.get(position).getQuestion_name());
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);
}
sh.single_radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int n = 0; n < group.getChildCount(); n++)
{
RadioButton rb = (RadioButton) group.getChildAt(n);
if (Integer.parseInt(option_list.get(n).getOption_id())== checkedId)
{
k++;
String result = rb.getText().toString();
sr=new SingleResult();
sr.setAns(result);
sr.setQuestion_id(question_list_array.get(k).getQuestion_id());
single_result.add(sr);
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
return;
}
}
}
});
v_final=v_single;
return v_final;
}
private class SingleHolder
{
TextView single_question_name;
RadioGroup single_radiogroup;
}
编辑: 这是 single_choice_layout.xml 文件:
<?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>
【问题讨论】:
-
@AnjaliTripathi。我们的问题不是改变单选按钮的位置。我们的问题是改变单选按钮在滚动时的选定状态。
-
它是一样的,因为我们在整个列表视图中使用单选按钮
-
可能也需要你的布局文件
-
@IbtehazShawon。我在编辑中添加了布局文件。