<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout ../..
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:showIn="@layout/activity_main">
<RelativeLayout android:id="@+id/l1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:background="@android:color/holo_blue_light"/>
<RelativeLayout android:id="@+id/l2"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_above="@+id/l1"
android:background="@android:color/holo_red_light"/>
</RelativeLayout>
我从这篇答案中借鉴了一种方法:
public void setMargin(View view) {
if (relativeLayout
.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams marginLayoutParams =
(ViewGroup.MarginLayoutParams) relativeLayout
.getLayoutParams();
int margin = relativeLayout.getHeight() / 2;
marginLayoutParams.setMargins(20, 0, 0, -margin);
relativeLayout.requestLayout();
}
}
为了演示,我在两个布局的两侧添加了边距,这样您就可以看到它们重叠的位置。如果浮动视图具有固定大小。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/a"
android:layout_alignParentBottom="true"
android:background="#44bb11"
android:layout_width="match_parent"
android:layout_height="100dp" />
<ImageView
android:layout_marginBottom="-40dp"
android:layout_above="@+id/a"
android:id="@+id/c"
android:background="#45000000"
android:layout_width="match_parent"
android:layout_height="80dp" />
</RelativeLayout>