2012-03-13 35 views
2

我试图动态创建一个TableLayout拥有其所有行拉伸像in this tutorial所示。我已经通过XML完成了它,但我想从活动中完成它。这里是我迄今试过的代码没有成功:安卓:在TableLayout拉伸行编程

public View getTableWithAllRowsStretchedView() { 
    LinearLayout linearLayout = new LinearLayout(this); 
    linearLayout.setOrientation(LinearLayout.VERTICAL); 
    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); 

    TableLayout tableLayout = new TableLayout(this); 
    tableLayout.setStretchAllColumns(true); 
    tableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT)); 
    tableLayout.setWeightSum(4); 


    for (int i = 0; i < 4; i++) { 
     TableRow tableRow = new TableRow(this); 
     tableRow.setGravity(Gravity.CENTER); 
     tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, 1.0f)); 

     for (int j = 0; j < 4; j++) { 
      Button button = new Button(this); 
      final int buttonNumber = (j + i * 4); 
      button.setText("" + buttonNumber); 
      button.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT)); 

      tableRow.addView(button); 
     } 
     tableLayout.addView(tableRow); 
    } 

    linearLayout.addView(tableLayout); 
    return linearLayout; 
} 

非常感谢您提前。

编辑

Screenshot of what I have 

enter image description here

what I expect 

enter image description here

+0

你可以添加当前和预期的屏幕截图吗? – waqaslam 2012-03-13 11:37:16

+0

有你有=) – 2012-03-13 12:03:11

回答

13

你行需要父母的LayoutParams

tableRow.setLayoutParams(new TableLayout.LayoutParams(
        TableLayout.LayoutParams.FILL_PARENT, 
        TableLayout.LayoutParams.FILL_PARENT, 1.0f)); 
+1

@slukain:你的答案是正确的,但只是一个简单的问题:如何知道哪个布局类需要使用?比如你用TableLayout替换了TableRow,为什么? – waqaslam 2012-03-13 12:14:42

+0

它工作!非常感谢您的帮助! – 2012-03-13 12:15:07

+4

@Waqas你需要父母的'LayoutParams'。按钮有'TableRow'参数,行有'TableLayout'参数,表中应该有'LinearLayout'参数(它与TableLayout一起工作,我认为是因为'TableLayout.LayoutParams'派生自' LinearLayout.LayoutParams',也是'TableLayout'是'LinearLayout'的扩展)。 – Luksprog 2012-03-13 12:41:09

0

Luksprog的答案是正确的。

用于拉伸水平,这样做:

TableRow tableRow = new TableRow(this); 
      tableRow.setLayoutParams(new TableLayout.LayoutParams(
        TableLayout.LayoutParams.FILL_PARENT, 
        TableLayout.LayoutParams.WRAP_CONTENT, 1.0f)); 

用于拉伸在垂直,这样做:

TableRow tableRow = new TableRow(this); 
      tableRow.setLayoutParams(new TableLayout.LayoutParams(
        TableLayout.LayoutParams.WRAP_CONTENT, 
        TableLayout.LayoutParams.FILL_PARENT, 1.0f)); 

用于拉伸的宽度和高度的布局,操作如下:

TableRow tableRow = new TableRow(this); 
      tableRow.setLayoutParams(new TableLayout.LayoutParams(
        TableLayout.LayoutParams.FILL_PARENT, 
        TableLayout.LayoutParams.FILL_PARENT, 1.0f));