Android开发中如何让TextView以自身中心为基准而非边框进行对齐
实现TextView以自身中心为基准对齐的两种方案
方案1:使用ConstraintLayout(推荐)
ConstraintLayout原生支持锚定控件中心位置,无需额外计算就能直接实现需求,设置的margin值会直接对应控件中心到父布局边缘的距离。
代码示例:
<androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/breakfastStats" android:layout_width="match_parent" android:layout_height="50dp" android:layout_below="@+id/breakfastAdd" android:layout_marginTop="1dp" android:background="@color/lightblack"> <TextView android:id="@+id/tvCarb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Carbohydrate" android:textColor="@color/white" android:layout_marginTop="5dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintLeft_margin="10dp" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/tvFat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fat" android:textColor="@color/white" android:layout_marginTop="5dp" app:layout_constraintRight_toRightOf="parent" app:layout_constraintRight_margin="10dp" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
方案2:沿用RelativeLayout适配
如果不想替换原有布局,可以通过添加透明占位锚点控件实现:先把占位控件放在你期望TextView中心所在的位置,再让TextView以占位控件为基准水平居中即可。
代码示例:
<RelativeLayout android:id="@+id/breakfastStats" android:layout_width="match_parent" android:layout_height="50dp" android:layout_below="@+id/breakfastAdd" android:layout_marginTop="1dp" android:background="@color/lightblack"> <View android:id="@+id/leftAnchor" android:layout_width="1dp" android:layout_height="1dp" android:layout_alignParentLeft="true" android:layout_marginLeft="10dp" android:layout_marginTop="5dp" android:visibility="invisible"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Carbohydrate" android:textColor="@color/white" android:layout_centerHorizontal="@id/leftAnchor" android:layout_alignTop="@id/leftAnchor" android:gravity="center"/> <View android:id="@+id/rightAnchor" android:layout_width="1dp" android:layout_height="1dp" android:layout_alignParentRight="true" android:layout_marginRight="10dp" android:layout_marginTop="5dp" android:visibility="invisible"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fat" android:textColor="@color/white" android:layout_centerHorizontal="@id/rightAnchor" android:layout_alignTop="@id/rightAnchor"/> </RelativeLayout>
内容的提问来源于stack exchange,提问作者KingSwoozie
相关产品推荐
相关产品推荐

