RelativeLayout重心不起作用

问题描述 投票:12回答:4

我试图在一个基础的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以获取其中一个视图,并且确实有效。但是,我无法使用此解决方案,因为我有两个并排的视图需要集中在一起。试图优化这个,所以我想避免嵌套布局,特别是线性,彼此内部。

有什么明显的东西让我失踪吗?我认为这个属性是针对这种情况做出的。

android center android-relativelayout gravity
4个回答
8
投票

我在没有使用嵌套ViewGroup的情况下回答了涉及三个视图的类似问题。

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>

5
投票

您需要将多个布局嵌套在一起。要将某些内容置于RelativeLayout中,您可以在子项上使用android:layout_centerInParent="true"。如果你试图让几个孩子居中,他们最终会在对方之下。

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


2
投票

将两个视图包装在LinearLayout中,然后将LinearLayout置于RelativeLayout中心,就像您对单个TextView所做的那样。


1
投票

所以我对这个问题的解决方法只是为了利用textview的复合drawable功能。我只是删除了按钮并使用drawableRight来显示搜索图标。

© www.soinside.com 2019 - 2024. All rights reserved.