我在代码中动态创建了TableRows
,我想为这些TableRows
设置边距。
我的TableRows
创建如下:
// 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);
如何动态设置这些边距?
答案 0 :(得分:67)
您必须正确设置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);
答案 1 :(得分:10)
这是有效的:
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再次传递布局参数!