2014-02-20 116 views
2

我有一个关于在TableLayout中不使用XML的问题。 有人已经和我一样问了,但是提供的答案一直无法帮到我。 how to set width of column dynamically in android tablelayout?宽度列动态列表布局

现在我有这个

TableLayout tl = (TableLayout) findViewById(R.id.TableLayout1); 
    /* Create a new row to be added. */ 
    TableRow tr = new TableRow(this); 
    tr.setLayoutParams(new TableRow.LayoutParams(
      TableRow.LayoutParams.FILL_PARENT, 
      TableRow.LayoutParams.WRAP_CONTENT)); 

    /* Create a Button to be the row-content. */ 
    Button b = new Button(this); 
    b.setText("Dynamic Button"); 
    b.setLayoutParams(new TableRow.LayoutParams(
      TableRow.LayoutParams.FILL_PARENT, 
      TableRow.LayoutParams.WRAP_CONTENT)); 
    /* Add Button to row. */ 

    tr.addView(b); 
    Button a = new Button(this); 
    a.setText("Dynamic Button"); 
    a.setLayoutParams(new TableRow.LayoutParams(
      TableRow.LayoutParams.FILL_PARENT, 
      TableRow.LayoutParams.WRAP_CONTENT)); 
    /* Add Button to row. */ 
    a.setGravity(2); 

    tr.addView(a); 

但我看不出如何改变

tr.setLayoutParams 

会做使得例如第一个按钮列70%的工作,另一个按钮30%

回答

1

您需要setLayoutParams到您的小部件,如下面的代码:

TableRow.LayoutParams tlp = new TableRow.LayoutParams(width,heigh); 
b.setLayoutParams(tlp); 

TableRow.LayoutParams tlp1 = new TableRow.LayoutParams(width/3,heigh/3); 
a.setLayoutParams(tlp1); 
+0

工作就像一个魅力,谢谢! –

2

您可以创建带重量的线性布局,并将这两个按钮保持在线性布局内,然后将线性设置为您的表格行。

检查下面的代码:

TableLayout tl = (TableLayout) findViewById(R.id.TableLayout1); 
    /* Create a new row to be added. */ 

    TableRow.LayoutParams params = new TableRow.LayoutParams(
      TableRow.LayoutParams.FILL_PARENT, 
      TableRow.LayoutParams.WRAP_CONTENT); 

    TableRow tr = new TableRow(this); 
    tr.setLayoutParams(params); 

    params = new TableRow.LayoutParams(0, 
      TableRow.LayoutParams.WRAP_CONTENT); 
    LinearLayout layout = new LinearLayout(this); 
    params.weight = 1; 
    layout.setLayoutParams(params); 
    layout.setBackgroundColor(Color.WHITE); 
    layout.setWeightSum(1); 

    /* Create a Button to be the row-content. */ 

    LinearLayout.LayoutParams chiledParams = new LinearLayout.LayoutParams(0, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 
    chiledParams.weight = (float) 0.7; 
    Button b = new Button(this); 
    b.setText("Button"); 
    b.setLayoutParams(chiledParams); 

    /* Add Button to row. */ 


    LinearLayout.LayoutParams chiledParams1 = new LinearLayout.LayoutParams(0, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 
    chiledParams1.weight = (float) 0.3; 
    Button a = new Button(this); 
    a.setText("Button"); 
    a.setLayoutParams(chiledParams1); 

    layout.addView(b); 
    layout.addView(a); 
    tr.addView(layout); 
    tl.addView(tr);