Create TableLayout programmatically

偶尔善良 提交于 2019-11-27 11:49:21
Grigori A.

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

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

clotilde

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?

John Moses

For me, to get mine I had to call addContentView().

Your problem is at this line:

b.setLayoutParams(new LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

You need to change LayoutParams to TableRow.LayoutParams:

b.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!