1

I'm using onClickListener to create a new table row in my table layout. I've defined all the values to my table row and it's working fine though I would like to add multiple rows.

    final TableLayout tl=(TableLayout)findViewById(R.id.tbl);
    final TableRow tr1 = new TableRow(this);
    final TextView textview1 = new TextView(this);
    final TextView textview2 = new TextView(this);
    final Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textview1.setText("B");
            textview1.setBackgroundResource(R.color.darkgrey);
            textview1.setGravity(Gravity.CENTER);
            textview1.setPadding(50, 50, 50, 50);
            textview2.setText("A");
            textview2.setBackgroundResource(R.color.darkgrey);
            textview2.setGravity(Gravity.CENTER);
            textview2.setPadding(50, 50, 50, 50);
            tr1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
            tr1.addView(textview1);
            tr1.addView(textview2);
            tl.addView(tr1);
        }
    });

XML

<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="*"
    android:id="@+id/tbl"
    android:layout_below="@+id/btn">

    <View
        android:layout_height="2dip"
        android:background="#FFFFFF" />
</TableLayout>

So I've clicked the button once and the new table row appears and after another click the app crashes.

How can I add multiple table rows into my table layout dynamically? I've thought using for loop, though I'm not sure about the right approach to apply it.

EDIT:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.none.myapplication, PID: 9775
                  java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

1 Answer 1

1

It's hard to tell without the exact error message, but I feel it's because you create final variables and then try to add them a second time. Have you tried creating the new table row and text views inside the OnClickListener?

Using a for loop would not be useful in your case as you really want the row to be created when it's clicked.

Sign up to request clarification or add additional context in comments.

2 Comments

You may look on the edit I have just made, it has error message there.
I just used another function to create row and it worked, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.