首页 > 解决方案 > 相对布局在左上角添加所有元素

问题描述

我添加了一个相对布局资源文件,每当我拖放一个元素时,它都会被设置到左上角。有任何解决这个问题的方法吗?

https://imgur.com/a/6FuAZe5

这是代码:

<?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">

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Switch" />
</RelativeLayout>

标签: androidandroid-relativelayout

解决方案


您可以添加属性android:gravity="center"来对齐里面的子元素RelativeLayout。这将使子元素与布局的中心对齐。此外,android:layout_centerInParent="true"您可以使用android:layout_alignParentTop="true"

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <!-- you need to align the button to a particular
        place in the layout -->
    <Button
        android:id="@+id/button5"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_margin="10dp"/>
    <!-- Then add layout_below/layout_above -->
    <Switch
        android:id="@+id/switch1"
        android:layout_below="@id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Switch Number 1"
        android:layout_margin="10dp"/>

</RelativeLayout>

您还可以设置多个值:android:gravity="bottom|right"。这会将孩子对齐到右下角。最后的话:了解RelativeLayout一下它以及如何使用它。 在此处输入图像描述


推荐阅读