这是一张图片,所以你可以理解我想要什么:
我已经在我的相对布局中设置了这个绿色元素,我想要的是将另一个元素(图片中的黑色元素)放在它上面,以便它正好位于绿色元素的中间。
请记住,黑色元素的宽度不是恒定的,它的宽度比绿色元素大。
有像 android:layout_alignLeft 和 android:layout_alignRight 这样的东西如果我想让它左对齐或右对齐会很有帮助,但据我所知没有 android:layout_alignCenter 所以我不知道该怎么做...
最佳答案
正如您自己所说,将这两个元素放在 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”有点可选)
或者在这里,不管其他 Views 位置如何:
<?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>
(在这种情况下,边距将定义第二个 View 宽度)
这是最终结果:
关于android - 如何将一个元素对齐到相对布局中另一个元素的中心和上方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452449/