15

这是一张图片,所以你可以理解我想要什么:

在此处输入图像描述

我已经在我的相对布局中设置了这个绿色元素,我想要在它上面放置另一个元素(图片中的黑色元素),这样它就可以准确地居中在绿色元素的中间。

请记住,黑色元素的宽度不是恒定的,它比绿色元素的宽度更大。

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

4

1 回答 1

23

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

然后,将两个元素的“ center_horizo​​ntal ”属性设置为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>

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

这是最终结果:

在此处输入图像描述

于 2013-08-26T20:31:30.883 回答