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.