RadioGroup中的动态单选按钮

时间:2014-10-07 15:31:24

标签: android dynamic radio-button radio-group

我试过用五种方法在一个RadioGroup中创建动态RadioButton,但总是有问题。我已经阅读了20个教程但没有...当我评论RadioGroup时,一切正常,但我可以选择所有的单选按钮......

这是我的代码:

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_login, container, false);

            //List of Radio Buttons
            final List<RadioButton> radioButtons=new ArrayList<RadioButton>();

            //RadioGroup
            RadioGroup radioGroup = new RadioGroup(getActivity());

            //LinearLayout 
            final LinearLayout linearLayout_chooseAccount=(LinearLayout)rootView.findViewById(R.id.chooseAccount_linearlayout);

            List views = new ArrayList();



            for(int i = 0;i < usersEmails.size();i++){

                View view = inflater.inflate(R.layout.fragment_chooseaccount_item,null);
                LinearLayout linearLayout = (LinearLayout)view.findViewById(R.id.chooseaccount_click);

                RadioButton radioButton = new RadioButton(getActivity());
                radioButtons.add(radioButton);
                radioGroup.addView(radioButtons.get(i));


                linearLayout.addView(radioGroup);


                TextView text = (TextView)view.findViewById(R.id.username2);
                text.setText(usersEmails.get(i)+"");

                views.add(view);
            }
           for(int i = 0; i < views.size(); i++)
           linearLayout_chooseAccount.addView((View) views.get(i));


   return rootView;

}

这是fragment_chooseaccount_item.xml:

   <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:maxWidth="120dp"
         android:textAppearance="?android:attr/textAppearanceLarge"
         android:text="User name"
         android:id="@+id/username2"
         android:layout_marginRight="10dp"
         android:layout_gravity="center_vertical"
         android:textSize="12sp"/>

这是xml:

<ScrollView
     android:layout_width="fill_parent"
     android:layout_height="170dp">
     <LinearLayout
        android:id="@+id/chooseAccount_linearlayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"></LinearLayout>

</ScrollView>

这是错误:

: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

1 个答案:

答案 0 :(得分:0)

看起来你的代码试图多次添加相同的视图:

List views = new ArrayList();

for(int i = 0;i < usersEmails.size();i++){

    View view = inflater.inflate(R.layout.fragment_chooseaccount_item,null);

    views.add(view);

}

for(int i = 0; i < views.size(); i++)
       linearLayout_chooseAccount.addView((View) views.get(i)); //This will fail