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

问题描述 投票:13回答:1

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

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

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

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

android android-layout alignment android-relativelayout
1个回答
19
投票

正如您自己所说,将两个元素放在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>

(“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>

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

这是最终结果:

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