如何在相对布局中将一个元素居中且位于另一个元素之上?

15

这里有一张图片,以便您了解我的需求:

enter image description here

我已经在相对布局中设置好了这个绿色元素,我想要的是将另一个元素(图片中的黑色元素)放置在其上方,以便它恰好居中于绿色元素的中心位置。

请注意,黑色元素的宽度不是固定的,而且比绿色元素的宽度要大。

虽然有像android:layout_alignLeft和android:layout_alignRight这样的选项可以帮助我将元素左对齐或右对齐,但据我所知,没有android:layout_alignCenter的选项,因此我不知道该如何做到这一点...


可能是重复的问题:Android相对布局从另一个视图alignCenter - tir38
1个回答

23

正如你所说,将两个元素都放在一个RelativeLayout中。

然后,将这两个元素的"center_horizontal"属性设置为true,然后将绿色元素的"below"属性设置为黑色元素的id。

这是完整的示例:

<?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" >

    <View
        android:id="@+id/view1"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:background="@color/Black"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <View
        android:id="@+id/view2"
        android:layout_height="100dp"
        android:layout_below="@+id/view1"
        android:background="@color/Green"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

("center_vertical"有点可选)

或者在这里,不管其他视图的位置如何:

<?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" >

    <View
        android:id="@+id/view1"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:background="@color/Black"
        android:layout_centerVertical="true" />

    <View
        android:id="@+id/view2"
        android:layout_width="40dp"
        android:layout_height="100dp"
        android:layout_below="@+id/view1"
        android:layout_alignLeft="@+id/view1"
        android:layout_alignRight="@+id/view1"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@color/Green" />

</RelativeLayout>

在这种情况下,边距将定义第二个视图的宽度。

这是最终结果:

输入图像描述


2
问题是center_horizontal将元素相对于其父元素居中。而我不希望它们位于父元素的中心,我只想将黑色元素与绿色元素对齐,无论它们在父元素中的位置如何。 - David Simka
将某物左右对齐真的很棒,谢谢。 - OFFmind
1
有没有不用硬编码的方法?我想让绿色与黑色居中对齐,而不管它们大小或绝对位置的变化。 - Noobification
@Remian8985,你可以将这两个元素放入一个独立的RelativeLayout中。在这两个元素上使用layout_centerHorizontal属性,并将第二个RelativeLayout定位到你想要的位置即可。 - AustrianDude

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接