Android开发问题:如何让TextView在LinearLayout内自动换行?
解决TextView在LinearLayout内无法自动换行并覆盖右侧控件的问题
问题核心在于包裹Address的LinearLayout未设置右侧约束,且LinearLayout宽度为wrap_content,导致它可无限向右延伸,TextView自然不会触发换行。只需两处修改即可解决:
- 给LinearLayout添加右侧约束,将其右端对齐到RightIcon的左端,同时设置
layout_width="0dp"(即match_constraint),让LinearLayout的宽度被限制在LeftIcon和RightIcon之间; - 给Address的TextView设置
android:layout_width="match_parent",让它填满LinearLayout的可用空间,触发自动换行。
修改后的完整代码:
<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- Header --> <TextView android:id="@+id/header" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!-- LeftIcon --> <Button android:id="@+id/leftIcon" android:layout_width="45dp" android:layout_height="45dp" android:text="X" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/header" app:layout_constraintBottom_toBottomOf="parent" /> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginLeft="10dp" android:layout_marginVertical="15dp" android:layout_marginRight="10dp" app:layout_constraintStart_toEndOf="@id/leftIcon" app:layout_constraintEnd_toStartOf="@id/rightIcon" app:layout_constraintTop_toBottomOf="@id/header" app:layout_constraintBottom_toBottomOf="parent" > <!-- Address --> <TextView android:id="@+id/address" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20sp" tools:text="An address which is very long and must wrap to a line bellow" /> <!-- Person 1 --> <TextView android:id="@+id/person1" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="Person 1" /> <!-- Person 2 --> <TextView android:id="@+id/person2" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="Person 2" /> </LinearLayout> <!-- RightIcon --> <Button android:id="@+id/rightIcon" android:layout_width="32dp" android:layout_height="32dp" android:text="Y" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/header" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
额外说明:
- 修复了原代码中
android:textSize=20sp"的引号缺失问题; - 添加的
android:layout_marginRight="10dp"用于让内容和RightIcon保持间距,避免拥挤,可按需调整或移除。
内容的提问来源于stack exchange,提问作者Mc_Topaz
相关产品推荐
相关产品推荐

