Andre Kraemer
Andre Kraemer

Reputation: 2761

Dynamically added Rows aren't visible

I recently started to play around with Android. One of the first things I tried to achieve was creating a dynamic TableLayout. Searching the web, I found some sample code at http://en.androidwiki.com/wiki/Dynamically_adding_rows_to_TableLayout which I copied into my activity.

So my Activity now looks like this:

public class FooActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.foo);

      /* Find Tablelayout defined in main.xml */
      TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout);

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

           /* Create a new row to be added. */
           TableRow tr = new TableRow(this);
           tr.setLayoutParams(new TableRow.LayoutParams(
                          LayoutParams.FILL_PARENT,
                          LayoutParams.WRAP_CONTENT));
           tr.setBackgroundColor(Color.MAGENTA);

                /* Create a Button to be the row-content. */
                Button b = new Button(this);
                b.setText("Dynamic Button");
                b.setLayoutParams(new LayoutParams(
                          LayoutParams.FILL_PARENT,
                          LayoutParams.WRAP_CONTENT));

                /* Add Button to row. */
                tr.addView(b);

      /* Add row to TableLayout. */
      tl.addView(tr,new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }
  }

}

my foo.xml in the layouts folder looks like this:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/myTableLayout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
>
 <TableRow
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">

      <Button android:text="Static Button"/>
 </TableRow>
</TableLayout>

When I now start my app in the emulator, none of the dynamically added rows are visible. I just see the static button which has been defined in the foo.xml file. With an attached debugger, I've been able to see that my code gets executed and the rows are added to the tablelayout object. However, the added rows aren't rendered.

Upvotes: 2

Views: 806

Answers (1)

Andre Kraemer
Andre Kraemer

Reputation: 2761

found the answer here: Dynamically add TableRow to TableLayout

I've added a wrong import with Eclipse. Changing it to the right one, as described in the question above, fixed by problem

Upvotes: 2

Related Questions