代码在Android中平均划分TableRow的空间

时间:2014-02-28 14:33:37

标签: java android android-tablelayout

我想在Android中平均分配Android中的TableRow空间。到目前为止,这是我完成的屏幕。 enter image description here

我希望“text 1 text 1 text 1”行占用相同的空间。我想从java代码中做到这一点。我的java代码如下:

public class History extends Activity implements View.OnClickListener {
    int counter=0;
    TableLayout TL ;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.history);        

        Button b1 = (Button) findViewById(R.id.Button01);
        b1.setOnClickListener(this);  
    } 

    public void onClick(View arg0) {
        TableLayout TL = (TableLayout) findViewById(R.id.table_layout); 
        TableRow row = new TableRow(this);
        counter++;

        TextView t = new TextView(this); 
        t.setText("text " + counter);

        TextView t1 = new TextView(this); 
        t1.setText("text " + counter);

        TextView t2 = new TextView(this); 
        t2.setText("text " + counter);

        // add the TextView and the CheckBox to the new TableRow

        row.addView(t);
        row.addView(t1);
        row.addView(t2);
        TL.addView(row,new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    }
}

我想实现以下屏幕。 enter image description here 我能做些什么来实现我的目标?

1 个答案:

答案 0 :(得分:2)

您想在weight中使用weightSumTableRow,并通过TextView设置TableLayout.LayoutParams来执行此操作。以下是一些带有相关注释的示例代码:

 TableRow row = new TableRow(this);
 row.setLayoutParams(
     new TableLayout.LayoutParams((LayoutParams.MATCH_PARENT, 
                                   LayoutParams.WRAP_CONTENT))
 // Set the weightSum of the row
 row.setWeightSum(1f);

 // Set the layout and weight for the columns. Note 0.5f gives us 0.5f+0.5f = 1f,
 // the weightSum set above. (Using two rows as an example).
 TableLayout.LayoutParams layoutParams = 
      new TableLayout.LayoutParams(0, 
                      LayoutParams.LayoutParams.WRAP_CONTENT, 0.5f);

 TextView t1 = new TextView(this); 
 t1.setText("text " + counter);
 // Set our layoutParams
 t1.setLayoutParams(layoutParams);

 TextView t2 = new TextView(this); 
 t2.setText("text " + counter);
 // Set our layoutParams
 t2.setLayoutParams(layoutParams);

 // Add views to row
 row.addView(t1);
 row.addView(t2);
 // Add row to table
 TL.addView(row);