0

コードから TableLayout に行を挿入しようとしています。インターネットとstackOverflowに関するいくつかのチュートリアルと、この例外が発生するたびにいくつかのチュートリアルを取得しました。

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)

アクティビティクラスは次のとおりです。

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>

私を助けてください。

4

1 に答える 1

0

あなたは間違っています

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

B は、テーブルの最初の行「t1」に既に追加されているため、ボタンです。ボタンはビューであり、各ビューは 1 つの親のみが保持できます。ボタン b は既に 1 行目に表示されています。それはrow2で再び表示できます。

ユーザーがボタンまたはrow1またはrow2をクリックするとロジックが作成されないため、どのボタンが押されたかを知る方法は? つまり、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. 

}

したがって、新しいボタン button2 を作成してから、row2 に追加する必要があります。

于 2011-12-12T12:54:33.860 に答える