16

我试图将几个视图水平居中在RelativeLayout一个基础上。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:background="@android:color/transparent" >

这是行不通的。我已经开始centerInParent接受true其中一种观点,并且确实奏效了。但是,我不能使用这个解决方案,因为我有 2 个并排的视图需要集中在一起。试图优化这一点,所以我想避免在彼此内部嵌套布局,尤其是线性布局。

我有什么明显的遗漏吗?我认为这个属性是为这种情况而设计的。

4

4 回答 4

14

我回答了一个类似的问题,涉及三个视图,但没有使用嵌套的 ViewGroups。

https://stackoverflow.com/a/13279846/1011746

这在 API 11 中进行了测试。

对于两个视图水平的情况:

<RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="center"
  android:background="@android:color/black"
  >
  <Button
    android:id="@+id/apply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="APPLY"
    android:textSize="20sp"
    />
  <Button
    android:id="@+id/undo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="UNDO"
    android:textSize="20sp"
    android:layout_toRightOf="@id/apply"
    />
</RelativeLayout>

对于两个视图垂直的情况:

<RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="center"
  android:background="@android:color/black"
  >
  <Button
    android:id="@+id/apply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="APPLY"
    android:textSize="20sp"
    />
  <Button
    android:id="@+id/undo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="UNDO"
    android:textSize="20sp"
    android:layout_below="@id/apply"
    />
</RelativeLayout>
于 2012-11-07T23:46:00.857 回答
10

您需要将多个布局嵌套在一起。要在 RelativeLayout 中居中,您可以android:layout_centerInParent="true"在子级上使用。如果你试图让几个孩子居中,他们最终会在彼此之下/之上。

因此,例如,您可以使用具有两个视图的 LinearLayout 作为 RelativeLayout 的子级,LinearLayout 具有android:orientation="horizontal"android:layout_centerInParent="true"。LinearLayout 现在应该在 RelativeLayout 中居中,两个孩子彼此相邻。

于 2012-06-05T21:06:16.877 回答
2

将两个视图包裹在一个 LinearLayout 中,然后像对单个 TextView 所做的那样,在 RelativeLayout 中将 LinearLayout 居中。

于 2012-06-05T21:07:16.583 回答
1

所以我对这个问题的修复结果只是利用了 textview 的复合可绘制特性。我只是删除了按钮并使用 drawableRight 来显示搜索图标。

于 2012-06-06T14:21:01.643 回答