stormzhang 的博客有一篇Tencent Interview , 其中有个问题是:如何让两个 TextView 在 RelativeLayout 中水平居中显示。我的第一反应是用一个 LinearLayout 包装它们。今天我想了另一种方法:
- 在水平中心放置一个占位 view,内容为空
- 在占位 view 的两侧各放置一个 view,并设置它们与占位 view 的 margin
为了显示更加清楚,我给 占位 view 和两侧的 view 都设置了背景,具体使用时可以去掉。布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@id/center"
android:layout_marginRight="10dp"
android:textSize="30sp"
android:text="name"
android:background="@android:color/holo_green_light"
/>
<TextView
android:id="@+id/center"
android:layout_width="1dp"
android:layout_height="20dp"
android:layout_centerInParent="true"
android:background="@android:color/holo_red_light"
/>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/center"
android:layout_marginLeft="10dp"
android:text="title"
android:textSize="30sp"
android:background="@android:color/holo_green_light"
/>
</RelativeLayout>
效果如下:
欢迎你提出更好的办法!