Android Studio 3.5.3:ConstraintLayout下视图与TextView水平对齐优化
解决ConstraintLayout中横线与TextView视觉对齐的最优方案
这问题我之前也碰到过!你现在手动设置34dp的layout_marginTop来对齐,本质是因为TextView的文字有基线和默认内边距,而横线View的边缘就是它的布局边界,直接按top对齐自然会视觉错位。不用手动补偿边距,用ConstraintLayout的垂直居中约束就能完美解决,下面是具体实现:
核心思路
让两个横线View与TextView垂直居中对齐,而不是都绑定到bt_login的bottom。这样ConstraintLayout会自动计算对齐位置,完全不需要手动调整margin值。
修改后的XML代码
<View android:id="@+id/lineRight" android:layout_width="0dp" android:layout_height="1dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toStartOf="@+id/tvOr" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" <!-- 关键:让横线与TextView垂直居中对齐 --> app:layout_constraintTop_toTopOf="@id/tvOr" app:layout_constraintBottom_toBottomOf="@id/tvOr" android:background="@android:color/darker_gray"/> <TextView android:id="@+id/tvOr" android:layout_width="wrap_content" android:layout_height="wrap_content" <!-- 移除手动设置的marginTop,改为绑定到bt_login的bottom --> app:layout_constraintTop_toBottomOf="@id/bt_login" <!-- 可选:去掉字体默认上下内边距,让对齐更精准 --> android:includeFontPadding="false" android:fontFamily="@font/roboto_regular" android:text="OR" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> <View android:id="@+id/lineLeft" android:layout_width="0dp" android:layout_height="1dp" android:layout_marginStart="16dp" app:layout_constraintStart_toEndOf="@+id/tvOr" app:layout_constraintEnd_toEndOf="parent" <!-- 同样设置垂直居中对齐TextView --> app:layout_constraintTop_toTopOf="@id/tvOr" app:layout_constraintBottom_toBottomOf="@id/tvOr" android:background="@android:color/darker_gray"/>
代码说明
- 移除了两个横线View的
layout_marginTop,以及TextView手动设置的34dpmarginTop - 给两个横线View添加
app:layout_constraintTop_toTopOf="@id/tvOr"和app:layout_constraintBottom_toBottomOf="@id/tvOr",让横线在垂直方向上与TextView居中对齐,视觉上就和文字的中线完全对齐了 - 可选添加
android:includeFontPadding="false"到TextView,移除Android字体默认的上下内边距,让对齐效果更精准
这样调整后,不管你后续修改TextView的字体大小、样式,或者调整bt_login的位置,三者都会自动保持水平对齐,完全不需要手动调整边距补偿。
内容的提问来源于stack exchange,提问作者ant2009
相关产品推荐
相关产品推荐

