How can I get an Android TableLayout to fill the screen?

后端 未结 5 1838
日久生厌
日久生厌 2020-12-13 19:11

I\'m battling with Android\'s awful layout system. I\'m trying to get a table to fill the screen (simple right?) but it\'s ridiculously hard.

I got it to work someho

5条回答
  •  我在风中等你
    2020-12-13 19:24

    There are two mistakes in the above discussion.

    1. It is possible to programatically set the weight by specifying TableLayout.LayoutParams and TableRow.LayoutParams and using the appropriate constructor, e.g.

      TableLayout.LayoutParams rowInTableLp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f);
      
    2. A widget must have the LayoutParams of its parent. Therefore, the rows must use TableLayout.LayoutParams.

    This gives you the following working version of your initial code:

    TableLayout table = new TableLayout(this);
    // Java. You succeed!
    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT);
    table.setLayoutParams(lp);
    table.setStretchAllColumns(true);
    
    TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT,
            1.0f);
    TableRow.LayoutParams cellLp = new TableRow.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT,
            1.0f);
    for (int r = 0; r < 2; ++r)
    {
        TableRow row = new TableRow(this);
        for (int c = 0; c < 2; ++c)
        {
            Button btn = new Button(this);
            btn.setText("A");
            row.addView(btn, cellLp);
        }
        table.addView(row, rowLp);
    }
    setContentView(table);
    

    Thanks to Romain Guy's comment on Android developer's forum for the solution.

提交回复
热议问题