Android布局:单行文本右对齐,多行左对齐的XML实现方案
Android实现TextView单行右对齐、多行左对齐(纯XML方案)
可以仅通过XML布局实现该效果,核心是利用ConstraintLayout的宽度约束特性,调整TextView的宽度、对齐偏置及文本重力属性,具体修改如下:
修改后的布局代码
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:text="Label" /> <TextView android:id="@+id/content" android:layout_width="0dp" android:layout_height="wrap_content" android:gravity="start" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@id/label" app:layout_constraintTop_toTopOf="@id/label" app:layout_constraintWidth_max="wrap" app:layout_constraintHorizontal_bias="1.0" tools:text="Lorem ipsum" /> </androidx.constraintlayout.widget.ConstraintLayout>
原理说明
android:layout_width="0dp":让TextView默认填充label右侧到父布局右侧的全部可用空间app:layout_constraintWidth_max="wrap":限制TextView的最大宽度为内容包裹宽度,当文本单行时,实际宽度会收缩为wrap_contentapp:layout_constraintHorizontal_bias="1.0":将收缩为wrap_content的TextView对齐到约束范围的最右侧,实现单行文本靠右的视觉效果android:gravity="start":当文本多行时,TextView填充全部可用空间,文本会左对齐显示,换行后的内容也从左侧开始
这样就完美匹配需求:单行时文本整体靠右,多行时文本左对齐且换行内容延续左侧起始位置。
内容的提问来源于stack exchange,提问作者suue
相关产品推荐
相关产品推荐

