2011-12-12 26 views
0

我试图从我的代码中插入TableLayout中的行。我在互联网和stackoverflow上有几个教程,以及每次我得到这个异常的时候。通过TableLayout中的代码插入tablerow时出现异常

12-12 17:54:07.027: E/AndroidRuntime(1295): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

12-12 17:54:07.027: E/AndroidRuntime(1295):  at com.kaushik.TestActivity.onCreate(TestActivity.java:41) 

这里是activityclass:

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     /* Find Tablelayout defined in main.xml */ 
     TableLayout tl = (TableLayout) findViewById(R.id.myTableLayout); 
     /* Create a new row to be added. */ 
     TableRow tr = new TableRow(this); 
     tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
       LayoutParams.WRAP_CONTENT)); 
     /* Create a Button to be the row-content. */ 
     Button b = new Button(this); 
     b.setText("Dynamic Button"); 
     b.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
       LayoutParams.WRAP_CONTENT)); 
     /* Add Button to row. */ 
     tr.addView(b); 
     /* Add row to TableLayout. */ 
     tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, 
       LayoutParams.WRAP_CONTENT)); 

     /* adding another row */ 
     TableRow tr2 = new TableRow(this); 
     tr2.addView(b); // Exception is here 
     tl.addView(tr2, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, 
       LayoutParams.WRAP_CONTENT)); 
    } 

这里是XML

<?xml version="1.0" encoding="utf-8"?> 
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/myTableLayout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
</TableLayout> 

请帮助我。

回答

0

你正在做的错

/* adding another row */ 
TableRow tr2 = new TableRow(this); 
tr2.addView(b); // Exception is here 

B是一个按钮,它在你的表格第一行“T1”已添加。由于按钮是一个视图,每个视图只能由一个父母持有。按钮b已经显示在第一行。它可以在第二行再次显示。

因为它不作逻辑,当用户点击按钮或ROW12行那么如何知道按下哪个按钮?我的意思是你不知道它被第1行或第2行压住。所以这是你意料之外的事情。

正如

onClick(View view){ 
    if(view == b){ 
     // So you cant do that this is button row1 button or row2 button. 
    } 

    // Or you can check the pressed button by id which will also be same. 

} 

所以,你应该创建新的Button按钮2,然后加入2行。

+0

:D那正是我想要的。谢谢谢谢非常感谢。 –

+0

是的,您可以在循环中添加新行,但您必须设法查看。我所说的是创建一个按钮阵列并逐一添加到行 – Arslan

相关问题