java - Android中TableRow空间均分的代码

标签 java android android-tablelayout

我想将Android中TableRow的空间平均分配给 children 。这是我到目前为止完成的屏幕。 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 我可以做什么来实现我的目标?

最佳答案

您想在TableRow中使用weightweightSum并通过TableLayout设置我们的TextView .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);

关于java - Android中TableRow空间均分的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22097996/

相关文章:

java - 在线程中设置事件监听器

android - 如何在相对布局中居中表格布局

java - 了解 Eclipse 中的外部 jar

java - android JVM 也可以在 PC 上运行吗?

java - 文件夹目录中的子文件夹数

java - Android Studio AddView TableLayout,必须removeChild错误?

android - java.lang.IllegalStateException : The specified child already has a parent. 您必须先在 child 的 parent 身上调用 removeView() [for a Table]

java - 为什么我的代码挂起?

java - 无法动态设置 setVisibility() 参数

java - 从 C 代码设置/获取 Java List<>