Android TextView文本覆盖兄弟视图时自动换行的实现方法
解决TextView文本覆盖右侧Switch的自动换行问题
直接修改布局即可实现需求,核心是限制左侧文本区域的宽度,让它只能占用Switch之外的剩余空间,具体修改如下:
<androidx.appcompat.widget.LinearLayoutCompat android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <!-- 左侧文本容器:设置0dp宽度+权重1,占据除右侧Switch外的所有空间 --> <androidx.appcompat.widget.LinearLayoutCompat android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <!-- 标题TextView:宽度设为match_parent,超出自动换行 --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Title that is very long and needs to wrap when it reaches the switch" android:textSize="13sp" /> <!-- 描述TextView:同样设为match_parent,自动换行 --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Description that is also very long and should wrap instead of overlapping the switch" android:textSize="12sp" /> </androidx.appcompat.widget.LinearLayoutCompat> <!-- 移除中间的空白View,不需要它了 --> <com.google.android.material.switchmaterial.SwitchMaterial android:layout_width="wrap_content" android:layout_height="wrap_content" /> </androidx.appcompat.widget.LinearLayoutCompat>
修改说明:
- 给左侧的垂直LinearLayout设置
android:layout_width="0dp"和android:layout_weight="1",这样它会自动填充父布局中除右侧Switch之外的所有可用宽度,不会无限扩展挤压Switch。 - 将两个TextView的
android:layout_width改为match_parent,让文本在左侧容器的宽度范围内自动换行,避免超出边界覆盖Switch。 - 移除了中间的空白权重View,因为左侧容器的权重已经实现了将Switch推到右侧的效果,无需额外占位View。
内容的提问来源于stack exchange,提问作者miechooy
相关产品推荐
相关产品推荐

