2012-09-11 70 views
7

我們正在編寫一個針對ICS +的應用程序,並且認爲GridLayout是最好的佈局範例,但似乎很少寫到它,而且我們遇到了一些對齊問題。Android中的水平居中視圖GridLayout

<GridLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/row_background" 
    android:rowCount="1" 
    android:columnCount="3" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:useDefaultMargins="true" 
    android:background="@drawable/list_item_bg"> 

    <ImageView 
     android:id="@+id/visibilityIcon" 
     android:layout_row="0" 
     android:layout_column="0" 
     android:src="@drawable/visibility_icon" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal"/> 

    <ImageView 
     android:id="@+id/windIcon" 
     android:layout_row="0" 
     android:layout_column="1" 
     android:src="@drawable/wind_icon" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal"/> 

    <ImageView 
     android:id="@+id/crosswindIcon" 
     android:layout_row="0" 
     android:layout_column="2" 
     android:src="@drawable/cloud_icon" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal"/> 

</GridLayout> 

但是,左側的2個圖標保持左對齊,最右側的圖標以剩餘空間爲中心。

基本上我們需要做的是將每列的大小指定爲總屏幕大小的1/3(因爲3列)。我認爲這是GridLayout所做的,但看起來'wrap_content'導致了這種行爲(合理),但'match_parent'會導致第一列填滿整個屏幕,而不是填充它的單元格,這是我所期望的行爲。

我們似乎已經嘗試過重力,layout_gravity等的每種組合,但是我們從根本上做錯了什麼,或者發現了GridLayout的限制。

感謝您的幫助!

+0

GridLayout似乎沒用! –

回答

8

只允許一行和一列在GridLayout中生長,並且這是沿着該軸的引力。如果多個行或列指定重力,則只有一個會得到它(如果我記得它是「最後一個」)。選擇另一種佈局或編寫自己的佈局。如果您只需要一個具有等分圖標的行,則可以使用LinearLayout,其中組件的寬度爲0px,重量完全相同。 1.

+0

感謝您的回答。出於好奇,你在哪裏找到了這個限制?我們將進一步調查,但看起來您在這裏可能是正確的。 – RealCasually

+0

與Android中的很多事情一樣,它是反覆試驗並閱讀源代碼)但實際上文檔中有一部分稱爲限制,其中包含以下句子:「GridLayout不支持體重原則,因爲因此一般來說,不能配置GridLayout來在多個組件之間分配多餘的空間。「 –

+0

謝謝。我知道我在這裏最初的問題不同 - 但是LinearLayout中的「weight」是我可能尋找的概念嗎?我的目標是將這些圖標以相等的間距均勻分佈在屏幕內。 – RealCasually