以编程方式设置TableRow的边距

20

我在代码中动态创建了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);

如何动态设置它们的边距?

2个回答

73

您需要正确设置LayoutParams。Margin是布局的一个属性,而不是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);

4
textView 的 setMargins 方法未定义。 - Jaseem
1
没有起作用。但下面@mik的答案有效,并且应该被接受为正确答案。 - Zvi
奇怪的是,在编程方式下,它需要双倍的边距,而在XML中手动输入则不需要。 - Vijay Kumar Kanta

14

这是有效的:

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 中,再次传递布局参数!


1
应该是被接受的答案。如果没有答案中的最后一行“yourTableLayoutInstance.addView(tr, lp);”,它就无法正常工作。 - Zvi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接