Android布局中TextView无法显示字符串资源与手动输入文本问题
问题原因
文本不显示和字符串资源长度、内容无关,核心是布局高度属性设置违反了ScrollView的测量规则:
- ScrollView作为垂直滚动容器,测量直接子元素时使用无约束高度规则,不允许直接子元素设置
android:layout_height="match_parent",否则会触发测量逻辑异常 - 你在LinearLayout内部的TextView也设置了
android:layout_height="match_parent",两层match_parent嵌套在ScrollView的测量逻辑下,会导致TextView实际测量高度异常、文本绘制区域偏移,最终看不到文字。
修复方案
修改两个高度属性即可,可选添加ScrollView的视口填充属性适配内容不足一屏的场景:
<ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <!-- 可选:内容高度小于屏幕时自动铺满,避免背景只包裹文字高度 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" <!-- 原match_parent修改为wrap_content --> android:orientation="vertical"> <TextView android:text="@string/zagalni" android:layout_width="match_parent" android:layout_height="wrap_content" <!-- 原match_parent修改为wrap_content --> android:background="#C9CC85" android:paddingTop="5dp" android:paddingBottom="5dp" <!-- 补充底部内边距,避免长文本滚动时底部贴边 --> android:paddingLeft="10dp" android:paddingRight="5dp" android:textSize="25sp" android:textColor="#455B2A"/> </LinearLayout> </ScrollView>
额外排查项(修改后仍不显示时检查)
- 检查对应页面的Kotlin/Java代码,是否存在手动调用TextView的
setText()方法传入空字符串,或者设置了导致文本清空的监听 - 确认没有其他同层级布局覆盖在TextView上层,你当前给出的布局结构不存在覆盖问题,优先修改高度属性即可
内容的提问来源于stack exchange,提问作者ded-logoped
相关产品推荐
相关产品推荐

