Android:实现双视图分置两侧无重叠且自适应内容
ConstraintLayout 双视图布局解决方案
最终实现代码
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/view1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="示例长文本:这是一段需要自动换行的超长内容,用来验证布局是否能满足文本换行且不与右侧视图重叠的要求" android:textSize="16sp" app:layout_constrainedWidth="true" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/view2" android:layout_marginEnd="8dp"/> <TextView android:id="@+id/view2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="右侧固定文本" android:textSize="16sp" app:layout_constrainedWidth="true" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toEndOf="@id/view1" android:layout_marginStart="8dp"/> </androidx.constraintlayout.widget.ConstraintLayout>
核心设置解析
- 分置布局两侧:
view1绑定父容器左边缘,view2绑定父容器右边缘,同时两者互相绑定对方的相邻边缘,确保固定在布局两端。 - 文本过长自动换行:添加
app:layout_constrainedWidth="true"属性,强制TextView在约束限定的可用空间内自动换行,避免宽度无限延伸挤压右侧视图。 - 保证互不重叠:双向约束配合宽度限制,让左侧TextView在宽度即将触及右侧视图时自动换行,再通过margin设置间距,彻底避免重叠。
- 消除空白点击区域:所有视图和父布局的宽高均设为
wrap_content,布局仅包裹实际内容,不会产生多余空白,点击事件只会触发在文本区域。
内容的提问来源于stack exchange,提问作者Chocos
相关产品推荐
相关产品推荐

