線性佈局中如何使實現元件之間有間隔
阿新 • • 發佈:2019-02-12
在研究android的Contacts原始碼的時候,遇到了一個佈局檔案,是用LinearLayout進行佈局的,先將程式碼貼上。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" > <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:text="scnu" android:textColor="?attr/call_log_primary_text_color" android:textSize="18sp" /> <TextView android:id="@+id/network_type" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="right" android:singleLine="true" android:text="cdma" android:textColor="?attr/call_log_secondary_text_color" android:textSize="14sp" /> </LinearLayout>
1. android:layout_weight 的使用
所有的檢視都有一個layout_weight值,預設為零,意思是需要顯示多大的檢視就佔據多大的螢幕空間。若賦一個大於零的值,則將父檢視中的可用空間分割,分割大小具體取決於每一個檢視的layout_weight值,以及該值在整個檢視屏幕布局的layout_weight值中所佔的比率而決定。 數值越大,佔用的空間越大。
2. android:gravity="right",只有在上面設定了layout_weight,將各控制元件分配了具體的大小,這個屬性才體現出效果。
當 android:orientation="vertical" 時,只有水平方向的設定才起作用,垂直方向的設定不起作用。即:left,right,center_horizontal 是生效的。
當 android:orientation="horizontal" 時,只有垂直方向的設定才起作用,水平方向的設定不起作用。即:top,bottom,center_vertical 是生效的。