Can't add a View to TableRow dynamically

472 views Asked by At

I am desperately trying to add an ImageView to a TableRow, but somehow I can't. I can add a new TableRow to the TableLayout, but to the Row I can't add anything. I already tried invalidating the row, or the View that I insert, but no difference.

Code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.page2,
            container, false);
    Button soundBtn = (Button) rootView.findViewById(R.id.p2b1);
    soundBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            LayoutInflater inflater = activity.getLayoutInflater();
            TableRow row = (TableRow)inflater.inflate(R.layout.page2, null).findViewById(R.id.p2row9);
            View child = (View)inflater.inflate(R.layout.dummyview, null);
            row.addView(child, 0);
        }
    });
}

and the XML is:

<TableLayout 
    android:id="@+id/p2table"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1" >
    <TableRow
        android:id="@+id/p2row9"
        android:layout_width="wrap_content"
        android:layout_height="200dip"
        android:paddingTop="10dip">
    </TableRow>
</TableLayout>

and my dummyview is:

<?xml version="1.0" encoding="utf-8"?>
        <View xmlns:android="http://schemas.android.com/apk/res/android"

            android:layout_width="0dp"
            android:layout_weight="0.3"
            android:layout_height="1dp"
            android:gravity="center"
            android:background="@color/textbody" />

Any help appreciated.

1

There are 1 answers

0
alijandro On

In the callback onClick, you don't have to inflate your layout at second time.

TableRow row = (TableRow) inflater.inflate(R.layout.page2, null).findViewById(R.id.p2row9);

Instead, use the root view to find TableRow directly.

TableRow row = (TableRow) rootView.findViewById(R.id.p2row9);