2014-01-25 53 views
1

這是較大的XML文件的縮寫版本,此處僅顯示四列中的一列。以線性佈局居中圖像

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:weightSum="4" > 

    <!-- 1st colum --> 

    <LinearLayout 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="1" 
     android:background="#ff0000" 
     android:orientation="vertical" 
     android:weightSum="4" > 

     <ImageButton 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:gravity="center" 
      android:layout_weight="1" 
      android:background="@null" 
      android:scaleType="fitCenter" 
      android:src="@drawable/myimage" /> 
    </LinearLayout> 

    <!-- 2nd colum --> 
    <!-- 3rd colum --> 
    <!-- 4th colum --> 

</LinearLayout> 

目前它放在這樣的:

enter image description here

我的問題

1)爲什麼不會在紅色的屏幕區域的中間圖像中心,儘管在圖像按鈕上使用了android:gravity="center"

2)如何將它置於該列中?

回答

2

使用

android:gravity="center" 

LinearLayout,並使用

android:layout_gravity="center" 
ImageButton

這告訴LinearLayout將其內容置於其本身的中心(垂直方向,因爲您設置的方向),並且它告訴圖像按鈕將它自己居中在它所分配的區域內。

+1

謝謝:)完美:) – oat

+1

其實,我只是玩弄了自己的android代碼,並且我認爲你甚至不需要在圖像按鈕上使用'android:layout_gravity ='center''。在LinearLayout上設置重力會考慮x和y方向。 – ArmaAK