2013-03-12 72 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); 
} 
相关问题