Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create TableLayout programmatically

I'm trying to create a TableLayout programatically. It just won't work. The same layout in an xml file works though. This is what I have:

public class MyTable extends TableLayout
{
    public MyTable(Context context) {
        super(context);

        setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        TableRow row = new TableRow(context);
        row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        Button b = new Button(getContext());
        b.setText("hello");
        b.setLayoutParams(new LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
        row.addView(b); 
        addView(row)
    }
}

...

// In main activity:
MyTable table = new MyTable(this);
mainLayout.addView(table);

When I run this, I don't get a crash, but nothing appears. If I get rid of the TableRow instance, at least the button does appear as a direct child of the TableLayout. What am I doing wrong?

like image 827
mark Avatar asked Oct 07 '09 01:10

mark


3 Answers

Just to make the answer more clear:

TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

TableLayout tableLayout = new TableLayout(context);
tableLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// assuming the parent view is a LinearLayout

TableRow tableRow = new TableRow(context);
tableRow.setLayoutParams(tableParams);// TableLayout is the parent view

TextView textView = new TextView(context);
textView.setLayoutParams(rowParams);// TableRow is the parent view

tableRow.addView(textView);

Explanation
When you call setLayoutParams, you are supposed to pass the LayoutParams of the parent view

like image 110
Grigori A. Avatar answered Nov 16 '22 00:11

Grigori A.


It turns out I needed to specify TableRowLayout, TableLayout etc for the layout params, otherwise the table just won't show!

like image 39
mark Avatar answered Nov 15 '22 22:11

mark


A good solution is to inflate layout files for each instance of row you want to create. See this post : How to duplicate Views to populate lists and tables?

like image 1
clotilde Avatar answered Nov 16 '22 00:11

clotilde