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

Android动态生成TextView无间距挤成一行显示异常求助

问题原因

  • 你调用setLayoutParams时新建的LinearLayout.LayoutParams未设置边距,直接覆盖了tviewlayout.xml中定义的10dp margin配置
  • 调用LayoutInflater.inflate()时传入null作为父布局参数,会导致XML根节点的布局属性(包含margin、宽高等)默认失效,即便不手动设置LayoutParams也无法拿到XML里的边距配置

解决方案

方案一(更推荐):修改inflate逻辑,删除手动设置LayoutParams的代码

正确传入父布局参数,让系统自动保留XML中的布局配置:

LinearLayout linearLayout =  (LinearLayout) binding.ll;
for (int i=0; i<arrSplit.length; i++) {
    // 第二个参数传入父布局,第三个参数传false表示不立即添加到父布局,会自动保留XML中的布局属性
    TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tviewlayout, linearLayout, false);
    tv.setText(arrSplit[i]);
    linearLayout.addView(tv);
}

方案二:手动给LayoutParams添加边距

如果需要动态修改布局参数,可以手动给新建的LayoutParams设置margin:

LinearLayout linearLayout =  (LinearLayout) binding.ll;
// 将10dp转换为像素单位,LayoutParams使用的是像素值
int marginPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
for (int i=0; i<arrSplit.length; i++) {
    TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tviewlayout, null);
    tv.setText(arrSplit[i]);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    // 按左、上、右、下顺序设置边距
    params.setMargins(marginPx, marginPx, marginPx, marginPx);
    tv.setLayoutParams(params);
    linearLayout.addView(tv);
}

两种方案都可以解决TextView无间距、挤在一起的问题。


内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:15:03