以编程方式设置TableRow的边距

ofi*_*rbt 18 android

我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);
Run Code Online (Sandbox Code Playgroud)

如何动态设置这些边距?

Sha*_*dul 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);
Run Code Online (Sandbox Code Playgroud)

  • textView怎么样?setMargins未定义为textView. (4认同)

ʞᴉɯ*_*ʞᴉɯ 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);
Run Code Online (Sandbox Code Playgroud)

您需要将TableRow添加到TableLayout再次传递布局参数!