java - 为什么相对 View 中的 margin top 和 layout_above 会这样?

标签 java android android-layout android-relativelayout

我试图将一个 View 放置在另一个 View 之上,并且稍微超出其边界框。
我的代码经过简化以显示问题:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">


    <View
        android:id="@+id/view"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:layout_above="@+id/linear"
        android:layout_marginTop="200dp"
        android:background="@color/red"
        />

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:orientation="vertical"
        android:padding="0dp"
        android:background="@color/white"
        >

        <View
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@color/orange"
            />
    </LinearLayout>    
</RelativeLayout>

结果:

enter image description here

第二个箭头显示了我期望的小矩形 View 的位置。
尽管我指定了与下面的线性布局相同的上边距,但为什么它显示在顶部?
如果我删除 android:layout_above="@+id/linear" 那么它会转到第二个箭头显示的位置,但位于橙色 View 下方而不是其上方。
为什么相对布局会这样做?

最佳答案

这样做的不是RelativeLayout,而是边距的本质。如果你放置一个 View (橙色框)并说其上方有 200dp 的边距,那么在该 200dp 边距内不能放置其他 View 。

要将橙色框居中,然后在其上方放置另一个 View ,您需要执行类似的操作。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <View
        android:id="@+id/view"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:layout_above="@+id/center_view"
        android:background="@color/red" />


    <View
        android:id="@+id/center_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:background="@color/orange" />


</RelativeLayout>

这会将橙色 View 置于中心,将红色 View 直接置于其顶部。请注意,您甚至不需要 LinearLayout,但可以直接在relativelayout 中拥有橙色 View 。

关于java - 为什么相对 View 中的 margin top 和 layout_above 会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512366/

相关文章:

android - Activity 暂停并重新创建后,如何停止 Activity 附加的 AlertDialog 继续出现在 Activity 上?

java - Activity 之间的Android数据检索

android - 如何检查 ImageView 是否在 android studio 中完成加载和图像

android - 从暂停恢复时全屏 TabActivity 出现问题

java - 使用 Java 8 Date/Time 类编写和测试便捷方法

java - 如何让GridBagLayout定位左上角

java - iOS 开发者的第一个 Android 应用程序

java - 不使用 goto 命令跳转到先前的代码

java - 我如何在 jsp 中使用 Math.pow?

java - main 函数可以使用 String 而不是 String[]