如何在TableRow android之间设置边距

时间:2012-06-23 09:36:08

标签: android

我找到了很多关于TableRow边距的解决方案,但是当我尝试行时根本没有边距。

这是我的代码:

        TableLayout table = (TableLayout)findViewById(R.id.myTableLayout);

        for (int i = 0; i < 3; i++) {
            TableRow tr = new TableRow(this);
            LayoutParams layoutParams = new LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            int leftMargin=110;
            int topMargin=100;
            int rightMargin=100;
            int bottomMargin=100;
            layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
            tr.setLayoutParams(layoutParams);
            tr.setBackgroundResource(R.drawable.shelf_bar);

            table.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT));
        }

这是我的预期结果:

enter image description here

请有人指出我的错误。感谢

2 个答案:

答案 0 :(得分: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再次传递布局参数!

答案 1 :(得分:0)

使用此可能

TableRow tr = new TableRow(this);  
TableLayout.LayoutParams tableRowParams=
  new TableLayout.LayoutParams
  (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.FILL_PARENT);

        int leftMargin=10;
        int topMargin=2;
        int rightMargin=10;
        int bottomMargin=2;

tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

tr.setLayoutParams(tableRowParams);