2013-03-13 71 views
0

此代碼有什麼問題?它給了我這個錯誤:動態添加線性佈局到另一個

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

final LinearLayout ll = new LinearLayout(this); 
    ll.setOrientation(LinearLayout.VERTICAL); 

    final LinearLayout ll2 = new LinearLayout(this); 
    ll2.setOrientation(LinearLayout.HORIZONTAL); 

     for(int i = 0; i < 20; i++) { 
      CheckBox cb = new CheckBox(getApplicationContext()); 
      TextView txt = new TextView(getApplicationContext()); 
       txt.setText("test!"); 
       ll2.addView(cb); 
       ll2.addView(txt); 
       ll.addView(ll2); //ERROR HERE 
      } 
     sc.addView(ll); 

回答

2

你打電話ll.addView(ll2)多次,因爲它是在循環。將它移到for循環之外:

final LinearLayout ll = new LinearLayout(this); 
ll.setOrientation(LinearLayout.VERTICAL); 

final LinearLayout ll2 = new LinearLayout(this); 
ll2.setOrientation(LinearLayout.HORIZONTAL); 

for(int i = 0; i < 20; i++) { 
    CheckBox cb = new CheckBox(getApplicationContext()); 
    TextView txt = new TextView(getApplicationContext()); 
    txt.setText("test!"); 
    ll2.addView(cb); 
    ll2.addView(txt); 
} 

ll.addView(ll2); 
sc.addView(ll); 
相關問題