简体   繁体   English

以编程方式设置TableRow的边距

[英]Programmatically set margin for TableRow

I have TableRows created dynamically in the code and I want to set margins for these TableRows . 我在代码中动态创建了TableRows ,我想为这些TableRows设置边距。

My TableRows created as follow: 我的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);

How do I dynamically set the margins for these? 如何动态设置这些边距?

You have to setup LayoutParams properly. 您必须正确设置LayoutParams。 Margin is a property of layout and not the TableRow , so you have to set the desired margins in the LayoutParams. 边距是布局的属性而不是TableRow,因此您必须在LayoutParams中设置所需的边距。

Heres a sample code: 下面是一个示例代码:

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);

This is working: 这是有效的:

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);

You need to add your TableRow to TableLayout passing the layout parameters again! 您需要将TableRow添加到TableLayout再次传递布局参数!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM