我有代码中dynamic创buildTableRows
,我想为这些TableRows
设置边距。
我的TableRows
创build如下:
// Create a TableRow and give it an ID TableRow tr = new TableRow(this); tr.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); Button btnManageGroupsSubscriptions = new Button(this); btnManageGroupsSubscriptions.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 40)); tr.addView(btnManageGroupsSubscriptions); contactsManagementTable.addView(tr);
我如何dynamic设置这些边距?
您必须正确设置LayoutParams。 保证金是布局的属性,而不是TableRow,所以您必须在LayoutParams中设置所需的保证金。
下面是一个示例代码:
TableRow tr = new TableRow(this); TableLayout.LayoutParams tableRowParams= new TableLayout.LayoutParams (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT); int leftMargin=10; int topMargin=2; int rightMargin=10; int bottomMargin=2; tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin); tr.setLayoutParams(tableRowParams);
这是工作:
TableRow tr = new TableRow(...); TableLayout.LayoutParams lp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(10,10,10,10); tr.setLayoutParams(lp); ------ // the key is here! yourTableLayoutInstance.addView(tr, lp);
你需要添加你的TableRow到TableLayout再次传递布局参数!