Android横向LinearLayout左TextView占满空间,如何让tv2固定在tv1右侧
方案1:ConstraintLayout 实现(推荐)
核心是给tv1开启约束宽度限制,同时设置双向水平约束保证tv2不会被挤出屏幕,短文本时tv2紧跟tv1右侧,长文本时tv1自动折行,tv2始终在tv1末尾右侧,代码如下:
<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="wrap_content"> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toStartOf="@id/tv2" app:layout_constrainedWidth="true" app:layout_constraintHorizontal_bias="0"/> <TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="*" app:layout_constraintStart_toEndOf="@id/tv1" app:layout_constraintBaseline_toBaselineOf="@id/tv1"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键属性说明:
app:layout_constrainedWidth="true":开启后tv1的宽度会受约束限制,当文本长度超过约束范围时不会撑破布局,自动折行app:layout_constraintHorizontal_bias="0":保证tv1始终左对齐,不会在水平约束空间内居中
方案2:LinearLayout 兼容实现
如果不想用ConstraintLayout,也可以通过LinearLayout的属性配置实现,代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="0dp"/> <TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="*"/> </LinearLayout>
该方案短文本场景下tv2会靠右对齐,适合对tv2位置没有严格紧跟要求的场景。
内容的提问来源于stack exchange,提问作者BoomingBones
相关产品推荐
相关产品推荐

