动态添加TableRow后layout_weight未生效,布局高度异常
Hey there! I see the issue you're facing—static TableRows in your TableLayout split the available space evenly, but the ones you add dynamically only take up the minimum height they need. Let's break down why this happens and how to fix it.
The Root Cause
When you use LayoutInflater.from(this).inflate(R.layout.tablerow, null), you're not providing the parent TableLayout as a context for the inflater. This means the inflater can't properly resolve the layout_weight="1" and layout_height="0dp" attributes on your TableRow—those properties rely on the parent's LayoutParams to calculate how much space to allocate. Without that parent reference, the TableRow defaults to wrapping its content.
The Fix
Update your inflate call to include the parent TableLayout and set attachToRoot to false. This tells the inflater to use the parent's LayoutParams rules when parsing your TableRow's layout attributes, while leaving the View detached so you can manually add it to the TableLayout afterward.
Here's the corrected code:
tl = findViewById(R.id.tabelle); // Pass the parent TableLayout as the second parameter, attachToRoot = false View view = LayoutInflater.from(this).inflate(R.layout.tablerow, tl, false); tl.addView(view);
Double-Check Your TableLayout Setup
Just to be thorough, make sure your TableLayout has these properties set correctly:
android:layout_height="match_parent"(or a fixed height, notwrap_content) so there's available space to distribute- If you also want columns to stretch evenly, add
android:stretchColumns="*"to your TableLayout XML
Why This Works
By passing the parent tl to inflate(), the inflater knows that the TableRow is going to be a child of a TableLayout. It then applies the layout_weight and layout_height rules as intended—making each dynamic TableRow take up an equal share of the TableLayout's available vertical space, just like your static rows.
内容的提问来源于stack exchange,提问作者MCH

