TableLayout (TableRow?) not sizing child Views as expected when adding them dynamically

后端 未结 3 560
-上瘾入骨i
-上瘾入骨i 2021-01-24 15:30

Context: I have a TableLayout (created using XML), which has one TableRow, which has one TextView. The code:

 

        
相关标签:
3条回答
  • 2021-01-24 16:11

    I think it's not a good idea to dynamically add an item to a TableRow - it defeats the purpose of using a table. Imagine if you add an item to the first row of the table, but not on the second, meaning the first row has more elements. It wouldn't look much like a table.

    But if you insist,

    From developer guide:

    The children of a TableRow do not need to specify the layout_width and layout_height attributes in the XML file. TableRow always enforces those values to be respectively MATCH_PARENT and WRAP_CONTENT.
    

    You may need to start looking on the layout_weight of each element. Try adding layout_weight=1 on the row's static elements, and then setting your dynamic RelativeLayout's weight to 1 before adding it to the row.

    rl.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f));
    

    The last parameter is weight.

    0 讨论(0)
  • 2021-01-24 16:21

    The problem is this behavior defined for TableRow:

    The children of a TableRow do not need to specify the layout_width and layout_height attributes in the XML file. TableRow always enforces those values to be respectively MATCH_PARENT and WRAP_CONTENT.

    Rather than add your text views directly to the TableRow, have the TableRow hold a horizontal LinearLayout and add the second view to that holder.

    (Also, using LinearLayout.LayoutParams for something that's going into a TableRow is wrong. You should have been using TableRow.LayoutParams. But that wouldn't be the way to get equal-width TextViews. Use a LinearLayout holder.)

    0 讨论(0)
  • 2021-01-24 16:22

    Set height like this to the layout containing the ScrollView. It solved my own problem where tablelayout does not show last lines.

    android:layout_height="0dp"

    0 讨论(0)
提交回复
热议问题