我试图将一个 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>
结果:
第二个箭头显示了我期望的小矩形 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/