通常情況下,如果我們想要兩個控件實現重疊的效果,一般都是使用FrameLayout 或者RelativeLayout布局。其實,如果設置兩個控件的margin值為負數,也能實顯控件重疊的效果。
先展示各種效果圖:
示例代碼1–對應上圖中的1:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<TextView
android:layout_width="180dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:background="#00ff00"
android:padding="-20dp"
android:text="這是沒加margin值的效果"/>
<TextView
android:layout_width="180dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:background="#678df7"
android:padding="10dp"
android:text="這是沒加margin值的效果"/>
</LinearLayout>
示例代碼2 –對應上圖中的2
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<TextView
android:layout_width="180dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:background="#00ff00"
android:padding="-20dp"
android:text="這是正的margin值的效果"/>
<TextView
android:layout_width="180dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:background="#678df7"
android:padding="10dp"
android:text="這是正的margin值的效果"/>
</LinearLayout>
示例代碼3 –對應上圖中3 的效果
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<TextView
android:layout_width="180dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:background="#00ff00"
android:padding="-20dp"
android:text="這是加了負的margin值的效果"/>
<!--通過這里設置的負的margin值,實現了左側tv覆蓋住右側tv一部分的效果-->
<TextView
android:layout_width="180dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_marginLeft="-30dp"
android:background="#678df7"
android:padding="10dp"
android:text="這是加了負的margin值的效果"/>
</LinearLayout>
示例代碼4 –對應上圖中的效果4
<!--消息提示的實現方式1 ,這種應該是實現未讀消息提醒布局最簡單的寫法-->
<RelativeLayout
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginTop="20dp"
android:background="@drawable/square_about_me">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="@drawable/red"
android:gravity="center"
android:text="99+"/>
</RelativeLayout>
示例代碼5 –對應上圖中的5
<!--消息提示的實現方式2,通過使用這種負的margin值的寫法,就可以靈活的調整右上角小紅點的位置-->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginTop="20dp">
<ImageView
android:id="@+id/iv1"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@drawable/square_about_me"/>
<!--通過設置負的margin值,實現小紅點覆蓋到小鈴鐺上的效果,並且可以通過調整margin值來調整小鈴鐺的位置-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="-30dp"
android:layout_toRightOf="@id/iv1"
android:background="@drawable/red"
android:gravity="center"
android:text="99+"/>
</RelativeLayout>
---------------------
原文:https://blog.csdn.net/north1989/article/details/52922564