Xml佈局

1、gravity和layout_gravity的區別

  • android:gravity用於設置View中內容相對於View組件的對齊方式,比方說button上的文字相對button本身的位置;LinearLayout中組件相對於LinearLayout本身是居中還是靠右還是靠左;而android:layout_gravity用於設置View組件相對於Container(佈局)的對齊方式,也就是這個組件相對於整個佈局要設置的位置;簡單來說,android.gravity是設置當前控件/佈局上的子控件;而android.layout_gravity用於設置當前控件/佈局相對於父組件/佈局的顯示位置;
  • 假如父佈局設置了gravity,那麼子組件如果再設置layout_gravity,則會使父組件設置的gravity失效
    layout_alignParentRight,當前組件與父組件右邊緣對齊
    android:scaleType=”fitCenter”,用於imageView,表示圖片按比例放大或縮小,並充滿imageView組件

2、設置一個組件靠右對齊

方法一 使用RelativeLayout,然後需要右對齊的組件裏,設置layout_alignParentRight =”true”即可實現右對齊;
此外,android:layout_centerVertical=”true”可以使當前組件垂直方向居中

方法二 使用LinearLayout,最後靠右的組件再使用一個LinearLayout包圍起來,並在此LinearLayout種設置gravity=”right”,表示其子組件都是右對齊
我們可以將要右對齊的控件放在另一個LinearLayout中,同時將其對齊方式設爲右對齊:android:gravity=”right”,還有一點,這個LinearLayout的寬度設爲充滿父控件:
android:layout_width=”fill_parent”。這樣就行了。

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:background="@drawable/bg"  
    android:orientation="horizontal" >  

    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="左邊1" />  

    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="左邊2" />  
    <!-- 將TextView包在另一個LinearLayout中  
         注意android:layout_width和android:gravity這兩個屬性  
     -->  
    <LinearLayout  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:gravity="right" >  

        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginRight="10dp"  
            android:text="右邊" />  
    </LinearLayout>  

</LinearLayout>  

3、weight屬性

如果要使用weight,那麼則必須把width或者height設置爲“0dp”,表明使用weight的另一種計算方法

4、LinearLayout

如果設置了gravity,則按照此設置了來計算子組件所佔用的空間,否則直接按照從左到右,並且子組件再去設置layout_gravity也沒有用了;按照自己的猜想,系統已經從左右到右把對應的空間設置好,你設置了靠右,其他空間就是那麼大,所有視覺看起來也就沒法再右了
5、RelativeLayout佈局
一個組件,如果不能顯示,有可能被其他組件蓋住了;例如前面有一個listview,並且沒有設定固定高度,而是match_parent;那麼其後的組件有可能會被list蓋住

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章