isatin
isatin

Reputation: 189

Fail to Move a View to a TableRow

I am trying to inflate a layout resource and move some views in it to a table. I remove the views from their parents and then add them to the table. It works but what I really need is to add them to a TableRow in the table instead. However, when I tried to do that, nothing showed up.

To simplify the example, I just use views in an xml instead of ones generated in code. In the following xml, there are a TableLayout with one TableRow and an ImageButton:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...>    

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/table">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/row_1"></TableRow>
    </TableLayout>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button" />

</RelativeLayout>

If I move the button to the table, it works:

Button button = (Button ) getActivity().findViewById(R.id.button);
TableLayout table = (TableLayout) getActivity().findViewById(R.id.table);
TableRow row  = (TableRow) getActivity().findViewById(R.id.row_1);

((ViewGroup)button.getParent()).removeView(button);
table.addView(button);

However, if I move it to the TableRow, the button won't show up.

row.addView(button);

Does anyone have a solution?

Upvotes: 1

Views: 110

Answers (1)

WannaBeGeek
WannaBeGeek

Reputation: 989

Try to add the Button to a row like this:

   row.addView(button,new TableRow.LayoutParams(
               TableRow.LayoutParams.WRAP_CONTENT,
               TableRow.LayoutParams.WRAP_CONTENT));

Upvotes: 1

Related Questions