標籤:技術分享 nbsp 實現 -- drawable 資源 分配 方便 relative
線性布局的weight屬性在等比例分配時比較方便,但是對複雜的介面,嵌套多層LinearLayout布局會導致渲染變慢,佔用更多系統資源;而使用RelativeLayout的話,可能僅僅需要一層就可以完成了,以父容器或者兄弟組件參考+margin +padding就可以設定組件的顯示位置。
1.容器定位
父容器定位屬性示意:
兄弟容器定位屬性示意:
舉例:梅花布局
實現代碼如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/RelativeLayout1" android:layout_width="match_parent" android:layout_height="match_parent" > <!-- 這個是在容器中央的 --> <ImageView android:id="@+id/img1" android:layout_width="80dp" android:layout_height="80dp" android:layout_centerInParent="true" android:src="@drawable/pic1"/> <!-- 在中間圖片的左邊 --> <ImageView android:id="@+id/img2" android:layout_width="80dp" android:layout_height="80dp" android:layout_toLeftOf="@id/img1" android:layout_centerVertical="true" android:src="@drawable/pic2"/> <!-- 在中間圖片的右邊 --> <ImageView android:id="@+id/img3" android:layout_width="80dp" android:layout_height="80dp" android:layout_toRightOf="@id/img1" android:layout_centerVertical="true" android:src="@drawable/pic3"/> <!-- 在中間圖片的上面--> <ImageView android:id="@+id/img4" android:layout_width="80dp" android:layout_height="80dp" android:layout_above="@id/img1" android:layout_centerHorizontal="true" android:src="@drawable/pic4"/> <!-- 在中間圖片的下面 --> <ImageView android:id="@+id/img5" android:layout_width="80dp" android:layout_height="80dp" android:layout_below="@id/img1" android:layout_centerHorizontal="true" android:src="@drawable/pic5"/> </RelativeLayout>
2. margin與padding的區別
margin表示組件到容器邊緣距離,如:marginleft = "5dp" 表示組件距離容器左邊緣5dp
padding代表的則是填充,例如:TextView設定paddingleft = "5dp",則是在組件裡的元素的左邊填充5dp的空間。
margin針對的是容器中的組件,而padding針對的是組件中的元素。
Android之布局RelativeLayout