Android TextView换行后右侧留白如何去除?聊天卡片开发问题
嘿,这个问题我之前做聊天卡片的时候也碰到过!你现在的TextView换行后右侧有留白,根源就是你设置的android:layout_marginRight="102dp"——这个属性会强制让TextView的右侧始终保留102dp的空白,哪怕文本换行后也不会自动收缩,所以才会出现绿线右侧的留白区域。
给你两个实用的解决方案,你可以根据自己的需求选:
方案一:移除固定右侧margin,改用maxWidth限制宽度
如果你希望TextView的背景只包裹文本,同时最大宽度不超过屏幕右侧102dp的位置,直接把layout_marginRight换成android:maxWidth就可以了,搭配layout_width="wrap_content"就能让文本换行后紧贴右侧:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/m" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxWidth="252dp" <!-- 这里的数值可以根据屏幕宽度计算,比如屏幕宽354dp的话,354-102=252,也可以用 dimens 适配不同屏幕 --> android:background="@color/red_700" android:padding="8dp" android:text="Teaasdasdasdasdasdasdas dasdasdasdasdasdasdas dasasdasdasdasdasdasdasdxt"/> </FrameLayout>
方案二:换用ConstraintLayout实现更灵活的宽度控制
如果你的布局可以换成ConstraintLayout,那这种方式适配性更好,既能限制TextView的最大右侧位置,又能让宽度完全自适应文本内容:
<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="match_parent"> <TextView android:id="@+id/m" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/red_700" android:padding="8dp" android:text="Teaasdasdasdasdasdasdas dasdasdasdasdasdasdas dasasdasdasdasdasdasdasdxt" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintWidth_max="wrap" android:layout_marginEnd="102dp"/> </androidx.constraintlayout.widget.ConstraintLayout>
这里通过layout_constraintEnd_toEndOf="parent"和layout_marginEnd="102dp"把TextView的最大右侧位置固定在离屏幕右边缘102dp的地方,layout_constraintWidth_max="wrap"则让TextView的宽度随文本内容自适应,不会超过这个限制,这样文本换行后背景就会紧紧包裹住文本,不会有多余的留白了。
简单说就是:layout_marginRight是给整个View加固定空白,而我们需要的是限制View的最大宽度,换用maxWidth或者ConstraintLayout的约束就能完美解决这个问题啦!
内容的提问来源于stack exchange,提问作者Zeon

