如何在相对布局中将元素对齐到另一个元素的中心和上方?

Dav*_*mka 13 android alignment android-layout android-relativelayout

这是一张图片,这样你就可以理解我想要的东西:

在此输入图像描述

我已经在我的相对布局中设置了这个绿色元素,我想要的是在它上面放置另一个元素(图中的黑色元素),使它完全位于绿色元素的中间.

请记住,黑色元素没有恒定的宽度,宽度大于绿色元素.

有像android:layout_alignLeft和android:layout_alignRight之类的东西,如果我想让它左右对齐会很有帮助,但据我所知没有android:layout_alignCenter所以我不知道怎么做这件事......

Phi*_*oda 20

正如您自己所说,将两个元素放在RelativeLayout中.

然后,将两个元素的" center_horizo​​ntal "属性设置为true,然后将green元素的" below "属性设置为black元素的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>
Run Code Online (Sandbox Code Playgroud)

("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>
Run Code Online (Sandbox Code Playgroud)

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

这是最终结果:

在此输入图像描述

  • 问题是 center_horizo​​ntal 将元素相对于它们的父元素居中。而且我不希望它们位于父元素的中心,我只想将黑色元素对齐到绿色元素的中心,而不管它们在父元素中的位置如何。 (2认同)