如何限制Android布局最大占屏宽60%且右对齐,解决短文本占满宽度问题
方案1:修正ConstraintLayout配置(最优解)
你遇到的短文本随机占满最大宽度的问题,主要是两个原因:一是animateLayoutChanges开启后动态更新文本时的布局测量异常,二是宽度约束的属性搭配错误。
正确的完整布局代码如下:
<?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" android:layout_marginTop="4dp" android:padding="4dp" android:animateLayoutChanges="true"> <TextView android:id="@+id/txtSentMsg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/rounded_corner" android:paddingStart="12dp" android:paddingEnd="12dp" android:paddingTop="8dp" android:paddingBottom="8dp" android:textColor="@color/white" android:textSize="16sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_default="wrap" app:layout_constraintWidth_max="60%" tools:text="Hello, this is a long message and will use other lines as i grows. The default width is 80% of any screen."/> </androidx.constraintlayout.widget.ConstraintLayout>
关键属性说明:
- 把
android:layout_width改回wrap_content,不要用0dp,搭配app:layout_constraintWidth_default="wrap",保证短文本时宽度适配内容 - 用
app:layout_constraintWidth_max="60%"直接限制最大宽度为父布局的60%,不需要额外加layout_constraintWidth_percent - 如果还是出现随机占满宽度的问题,给TextView加一行
android:layout_gravity="end",或者在代码里动态设置文本后主动调用txtSentMsg.requestLayout()触发重新测量即可。
方案2:如果坚持用RelativeLayout实现
如果不想换ConstraintLayout,也可以通过给内层RelativeLayout加最大宽度限制实现,需要在代码里动态计算屏幕宽度设置maxWidth:
- 先给内层RelativeLayout加id:
android:id="@+id/msgContainer" - 在代码里动态设置最大宽度:
// Kotlin代码示例 val displayMetrics = resources.displayMetrics val maxWidth = (displayMetrics.widthPixels * 0.6f).toInt() msgContainer.maxWidth = maxWidth
// Java代码示例 DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int maxWidth = (int) (displayMetrics.widthPixels * 0.6f); msgContainer.setMaxWidth(maxWidth);
内容的提问来源于stack exchange,提问作者Karmveer Singh
相关产品推荐
相关产品推荐

