android LinearLayout和RelativeLayout實現精確佈局

先明確幾個概念的區別: 
padding margin:都是邊距的含義,關鍵問題得明白是什麼相對什麼的邊距
padding:是控件的內容相對控件的邊緣的邊距. 

margin  :是控件邊緣相對父空間的邊距android

android:gravity是對該view 內容的限定.佈局

好比一個button 上面的text. 你能夠設置該text 在view的靠左,靠右等位置.該屬性就幹了這個. spa

android:layout_gravity 是用來設置該view中的子view相對於父view的位置.code

好比一個button 在linearlayout裏,你想把該button放在靠左,靠右等位置就能夠在linearlayout中經過該屬性設置xml

 

XML 佈局文件blog

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="horizontal" 
 4     android:layout_width="fill_parent"
 5     android:layout_height="wrap_content" 
 6     android:gravity="center_vertical">
 7     
 8     <ImageView android:id="@+id/ivLogo" 
 9         android:layout_width="50dp"
10         android:layout_height="50dp" 
11         android:src="@drawable/icon"
12         android:paddingLeft="5dp" />
13         
14     <RelativeLayout android:id="@+id/rl_name"
15         android:layout_width="wrap_content" 
16         android:layout_height="wrap_content"
17         android:gravity="right" 
18         android:padding="10dp">
19         
20         <TextView android:id="@+id/tvApplicationName"
21             android:layout_width="wrap_content" 
22             android:layout_height="wrap_content"
23             android:textSize="16dp" />
24     </RelativeLayout>
25     
26     <RelativeLayout android:id="@+id/rl_score"
27         android:layout_width="fill_parent" 
28         android:layout_height="wrap_content"
29         android:gravity="right" 
30         android:padding="10dp">
31         
32         <TextView android:id="@+id/tvRating" 
33         android:layout_width="wrap_content"
34             android:layout_height="wrap_content" 
35             android:text="5.0" />
36             
37         <RatingBar android:id="@+id/ratingbar" 
38             android:layout_width="wrap_content"
39             android:layout_height="wrap_content" 
40             android:numStars="5"
41             style="?android:attr/ratingBarStyleSmall" 
42             android:layout_below="@id/tvRating" />
43     </RelativeLayout>
44     
45 </LinearLayout>

上面佈局文件的效果圖utf-8

 

上面的佈局文件是一個ListView中的list_item佈局,在一個ListView中顯示全部的APK資源,每一個資源項顯示圖標,名稱及評分。資源

在listItem的最外層LinearLayout中加android:gravity="center_vertical",設定內容垂直居中顯示。it

在id爲rl_score的RelativeLayout中設定android:layout_width="fill_parent"來填充剩餘空間;io

android:gravity="right"設定內容相對於rl_score右對齊;

android:padding="10dp"設定RelativeLayout中的內容相對RelativeLayout的邊緣的邊距爲10dp。 這個佈局雖然簡單,但倒是常常用到的。

相關文章
相關標籤/搜索