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

标签 android android-layout alignment android-relativelayout

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

enter image description here

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

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

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

最佳答案

正如您自己所说,将这两个元素放在 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”有点可选)

或者在这里,不管其他 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 宽度)

这是最终结果:

enter image description here

关于android - 如何将一个元素对齐到相对布局中另一个元素的中心和上方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452449/

相关文章:

html - 需要 css 对齐问题的解决方案/支持

css - 正确对齐元素

python - 关于python中字符串格式化的几个问题。结盟

android - 更新时列出崩溃的应用程序

android - 如何在 Android 中将 Imageview 置于 Listview 下方?

Android - 显示电话簿联系人并选择一个

android - 为什么AlertDialog.Builder 为自定义布局(Tablelayout)显示半空对话框

android - 如何处理用户对 ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 的回答?

java - BroadcastReceiver 中的 AlertDialog??可以吗?

android - 车身可调速度AndEngine/Box2D