2014-01-25 77 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