2013-03-12 65 views
0

我有這樣的代碼,我要動態添加嵌套嵌套在RelativeLayout的內部滾動型內的LinearLayout(RelativeLayout-> ScrollView-> LinearLayout->我ChechBoxes)動態添加的LinearLayout成的RelativeLayout

li = (RelativeLayout) findViewById(R.id.mainlayout);  
ScrollView sv = new ScrollView(this); 
final LinearLayout ll = new LinearLayout(this); 
ll.setOrientation(LinearLayout.VERTICAL); 
li.addView(sv); 
sv.addView(ll); 
for(int i = 0; i < 20; i++) { 
    CheckBox cb = new CheckBox(getApplicationContext()); 
    cb.setText("I'm dynamic!"); 
    ll.addView(cb); 
} 
this.setContentView(sv); 
裏面的CheckBox

,但我得到這個錯誤:

03-12 20:32:14.840: E/AndroidRuntime(945): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

我的RelativeLayout在我的XML文件中聲明已經 我是如何解決這一問題?

回答

2
this.setContentView(sv); 

這將嘗試你的滾動型添加到FrameLayout裏android.R.id.content,但你已經取得lisv父......因此,「指定的小孩已經有母。」

我相信你可以刪除 this.setContentView(sv); 因爲它看起來像你只想增加了滾動(等)到RelativeLayout的,而不是更換整個現有佈局。

+0

它不工作 – Fcoder 2013-03-12 21:50:53

+0

我對不起,閱讀,但我怎麼可以幫助你沒有任何有關_why_它不起作用的信息?我無法從這裏看到您當前的代碼或錯誤... – Sam 2013-03-12 21:55:29

0

入住這http://developer.android.com/training/animation/screen-slide.html 當你下載示例應用程序,經過LayoutChangesActivity.java

以下是代碼添加項目..

private void addItem() { 
    // Instantiate a new "row" view. 
    final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
      R.layout.list_item_example, mContainerView, false); 

    // Set the text in the new row to a random country. 
    ((TextView) newView.findViewById(android.R.id.text1)).setText(
      COUNTRIES[(int) (Math.random() * COUNTRIES.length)]); 

    // Set a click listener for the "X" button in the row that will remove the row. 
    newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      // Remove the row from its parent (the container view). 
      // Because mContainerView has android:animateLayoutChanges set to true, 
      // this removal is automatically animated. 
      mContainerView.removeView(newView); 

      // If there are no rows remaining, show the empty view. 
      if (mContainerView.getChildCount() == 0) { 
       findViewById(android.R.id.empty).setVisibility(View.VISIBLE); 
      } 
     } 
    }); 

    // Because mContainerView has android:animateLayoutChanges set to true, 
    // adding this view is automatically animated. 
    mContainerView.addView(newView, 0); 
} 
相關問題