Adding Table rows Dynamically in Android

android, android-layout

Solution

You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:

    public void init(){
    TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);


    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        checkBox = new CheckBox(this);
        tv = new TextView(this);
        addBtn = new ImageButton(this);
        addBtn.setImageResource(R.drawable.add);
        minusBtn = new ImageButton(this);
        minusBtn.setImageResource(R.drawable.minus);
        qty = new TextView(this);
        checkBox.setText("hello");
        qty.setText("10");
        row.addView(checkBox);
        row.addView(minusBtn);
        row.addView(qty);
        row.addView(addBtn);
        ll.addView(row,i);
    }
}

Problem

I am trying to create a layout where I need to add table rows dynamically. Below is the table layout xml ``` <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/displayLinear" android:background="@color/background_df" android:orientation="vertical" > <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/display_row" android:layout_marginTop="280dip" > </TableLayout> ``` The activity file where rows are being added dynamically is ``` public void init(){ menuDB = new MenuDBAdapter(this); ll = (TableLayout) findViewById(R.id.displayLinear); TableRow row=(TableRow)findViewById(R.id.display_row); for (int i = 0; i <2; i++) { checkBox = new CheckBox(this); tv = new TextView(this); addBtn = new ImageButton(this); addBtn.setImageResource(R.drawable.add); minusBtn = new ImageButton(this); minusBtn.setImageResource(R.drawable.minus); qty = new TextView(this); checkBox.setText("hello"); qty.setText("10"); row.addView(checkBox); row.addView(minusBtn); row.addView(qty); row.addView(addBtn); ll.addView(row,i); } } ``` But when I run this, I am getting below error ``` 08-13 16:27:46.437: E/AndroidRuntime(23568): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roms/com.example.roms.DisplayActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. ``` I understand that this is due to command `ll.addView(row,i);` but when I remove this its adding all stuff in a single row rather tan creating a new row for next item. I tried with giving index too as `row.addView(addBtn,i)` but still its not populating correctly. Please advise. Thanks.

Original source