You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态添加TableRow后layout_weight未生效,布局高度异常

Fix: Dynamically Added TableRows Not Taking Equal Space in TableLayout

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, not wrap_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:24:20