LinearLayout中长文本TextView导致左侧控件被挤出屏幕的解决方法
解决LinearLayout横向布局中间文本过长挤走左右TextView的问题
这问题我之前做列表项布局的时候碰到过,不想用android:weight的话,ConstraintLayout是最适合的方案——它能让中间的TextView自动占据左右两个TextView之外的剩余空间,文本过长时自动换行,完全不用预先定义比例,完美适配各种屏幕。
替换为ConstraintLayout的实现代码
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 左侧TextView:固定宽度,靠父布局左侧对齐 --> <TextView android:id="@+id/item_left" android:layout_width="40dp" android:layout_height="40dp" android:text="LEFT" android:gravity="center" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> <!-- 中间TextView:自适应剩余宽度,文本过长自动换行 --> <TextView android:id="@+id/item_middle" android:layout_width="0dp" <!-- 关键:用0dp匹配约束规则 --> android:layout_height="wrap_content" android:background="#aaaaaa" android:text="This is a very very long text which is so long that it wraps but unfortunatelly also pushes the TextView with ID item_right off the screen." app:layout_constraintStart_toEndOf="@+id/item_left" app:layout_constraintEnd_toStartOf="@+id/item_right" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> <!-- 右侧TextView:包裹内容,靠父布局右侧对齐 --> <TextView android:id="@+id/item_right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RIGHT" android:gravity="center" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
关键逻辑说明
- 左侧TextView通过
app:layout_constraintStart_toStartOf="parent"固定在父布局左侧,高度和父布局上下对齐; - 右侧TextView通过
app:layout_constraintEnd_toEndOf="parent"固定在父布局右侧,高度同步对齐; - 中间TextView的宽度设为
0dp(对应ConstraintLayout的match_constraint模式),同时用app:layout_constraintStart_toEndOf="@+id/item_left"和app:layout_constraintEnd_toStartOf="@+id/item_right"把它夹在左右两个控件之间,这样它会自动占据剩余的可用宽度,文本过长时会自动换行,绝不会挤走左右的TextView。
如果坚持用LinearLayout的替代方案
如果不想更换布局容器,也可以给中间的TextView设置android:maxWidth,但这个需要手动计算屏幕宽度减去左右两个TextView的宽度,灵活性很差(比如不同屏幕尺寸、左右TextView内容变化时都要调整数值),示例如下:
<!-- 仅修改中间TextView的属性 --> <TextView android:id="@+id/item_middle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#aaaaaa" android:maxWidth="200dp" <!-- 手动设置最大宽度,需根据实际场景调整 --> android:text="This is a very very long text which is so long that it wraps but unfortunatelly also pushes the TextView with ID item_right off the screen." android:layout_gravity="left|center_vertical" />
但这种方案局限性很大,还是ConstraintLayout的自适应方式更靠谱。
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

