1.核心屬性圖
其實通過這張圖我們大概就知道RelativeLayout怎么用了想际,基本概括了所有揍鸟,所以我們就講一些其他的用法
2.margin與padding的區(qū)別
初學(xué)者對于這兩個屬性可能會有一點混淆瘟滨,這里區(qū)分下: 首先margin代表的是偏移,比如marginleft = "5dp"表示組件離容器左邊緣偏移5dp; 而padding代表的則是填充,而填充的對象針對的是組件中的元素,比如TextView中的文字 比如為TextView設(shè)置paddingleft = "5dp",則是在組件里的元素的左邊填充5dp的空間! margin針對的是容器中的組件膨疏,而padding針對的是組件中的元素致稀,要區(qū)分開來! 下面通過簡單的代碼演示兩者的區(qū)別:
比較示例代碼如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Button"/>
<Button
android:paddingLeft="100dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Button"
android:layout_toRightOf="@id/btn1"/>
<Button
android:id="@+id/btn2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Button"
android:layout_alignParentBottom="true"/>
<Button
android:layout_marginLeft="100dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Button"
android:layout_toRightOf="@id/btn2"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
運行效果圖比較:
3.很常用的一點:margin可以設(shè)置為負數(shù)
相信很多朋友都不知道一點吧赚窃,平時我們設(shè)置margin的時候都習(xí)慣了是正數(shù)的, 其實是可以用負數(shù)的,下面寫個簡單的程序演示下吧,模擬進入軟件后,彈出廣告 頁面的,右上角的cancle按鈕的margin則是使用負數(shù)的册招!
效果圖如下:
貼出的廣告Activity的布局代碼吧,當然,如果你對這個有興趣的話可以下下demo, 因為僅僅是實現(xiàn)效果,所以代碼會有些粗糙!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jay.example.relativelayoutdemo.MainActivity"
android:background="#00CCCCFF">
<ImageView
android:id="@+id/imgBack"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:background="@drawable/myicon" />
<ImageView
android:id="@+id/imgCancle"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_alignRight="@id/imgBack"
android:layout_alignTop="@id/imgBack"
android:background="@drawable/cancel"
android:layout_marginTop="-15dp"
android:layout_marginRight="-10dp" />
</RelativeLayout>