2011-12-12 54 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