2014-10-07 75 views
0

我嘗試過使用五種方法在一個RadioGroup中創建動態RadioButton,但總是遇到問題。我已閱讀20個教程,但沒有...當我有評論RadioGroup中,一切正常,但我可以選擇所有單選按鈕...RadioGroup中的動態RadioButtons

這是我的代碼:

 @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. 

回答

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 
相關問題