ListView中的RadioButton给出了IllegalStateException

时间:2014-03-03 04:06:10

标签: android android-listview illegalstateexception android-radiogroup android-radiobutton

我希望RadioButton位于ListView内,问题是RadioButton中填充的每个ListView都有RadioGroup,因为所有RadioButton都可以被选中。我只想选择一个项目,并将其位置的checkFlag设置为true,将其他位置设置为false。我使用addView添加了java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.,但触发了getView

这是我的@Override public View getView(final int position, View convertView, ViewGroup parent) { View row = convertView; holder = null; final Option optionItem = data[position]; protected int selectedPosition = -1; protected boolean selectedCheckFlag = false; if (row == null) { LayoutInflater inflater = ((Activity) context) .getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new OptionHolder(); holder.radioGroup = (RadioGroup) row .findViewById(R.id.radiogroup_survey); holder.radioButton = (RadioButton) row .findViewById(R.id.radiobutton_survey); row.setTag(holder); } else { holder = (OptionHolder) row.getTag(); } holder.radioGroup.setOrientation(RadioGroup.VERTICAL); holder.radioButton.setText(optionItem.option); holder.radioGroup.addView(holder.radioButton); // Triggered IllegalStateException holder.radioGroup .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub RadioButton selectedRadio = (RadioButton) findViewById(checkedId); Toast.makeText(getApplicationContext(), selectedRadio.getText().toString(), Toast.LENGTH_SHORT).show(); optionItem. selectedCheckFlag = true; selectedPosition = position; if (selectedPosition > -1 && selectedCheckFlag) optionItem.checkFlag = true; else optionItem.checkFlag = false; } }); return row; }

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent_radio"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<RadioGroup
    android:id="@+id/radiogroup_survey"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radiobutton_survey"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:button="@drawable/selector_checkbox_red"
        android:textColor="@color/brown" />
</RadioGroup>

这是项目布局:

{{1}}

1 个答案:

答案 0 :(得分:0)

因为您已使用xml在RadioButton中添加了RadioGroup所以无需再次添加相同的按钮。评论addView行:

// holder.radioGroup.addView(holder.radioButton)
  

问题是ListView中填充的每个RadioButton都有   不同的RadioGroup因为它们都可以被选中。我只想要   要选择一个项目并将其位置的checkFlag设置为true和   其他位置为假

取消选中RadioGroup使用clearCheck()的{​​{1}}方法的所有单选按钮:

RadioGroup