【问题标题】:Programmatically set margin for TableRow以编程方式为 TableRow 设置边距
【发布时间】:2014-06-20 23:13:05
【问题描述】:

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

如何动态设置这些边距?

【问题讨论】:

    标签: android


    【解决方案1】:

    您必须正确设置 LayoutParams。 Margin 是 layout 的属性,而不是 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);
    

    【讨论】:

    • textView 怎么样? setMargins 未定义 textView。
    • 没有用。但是下面@mik 的答案有效,应该是公认的答案
    • 奇怪,编程方式需要双倍边距,就像手动输入 xml 一样。
    【解决方案2】:

    这是有效的:

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

    【讨论】:

    • 应该是公认的答案。没有答案中的最后一行,它不起作用'yourTableLayoutInstance.addView(tr,lp);'。