2017-04-14 76 views
11

我正在Android Studio上製作遊戲,並且存在Grid View組件的問題。我無法將網格視圖內的項目居中對齊,如After圖像。我嘗試了幾種方法,如android:stretchModeandroid:layout_centerHorizontal,但它沒有幫助。這裏是我的XML代碼:Gridview中的居中對齊項目

<RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:background="@android:color/holo_orange_light" 
     android:layout_weight="8" 
     android:layout_gravity="center"> 

     <GridView 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_margin="10px" 
      android:id="@+id/gridAnswersChar" 
      android:numColumns="8" 
      android:gravity="center"> 
     </GridView> 

</RelativeLayout> 

前:

enter image description here

後:

enter image description here

+0

你有沒有找到解決方案? – FiXiT

+0

我還不知道:( –

+0

很想看到這個答案。面對同樣的問題。 – lostintranslation

回答

10

希望這不是一個嚴格的要求,爲你,你使用GridView,如我相信你所尋找的東西本質上是不可能的。但是,如果您願意使用RecyclerView代替,我爲您提供了一個解決方案。

該解決方案將利用FlexboxLayoutManager,谷歌的FlexboxLayout項目的一部分:https://github.com/google/flexbox-layout

我的解決方案的完整代碼在這裏看到: https://gist.github.com/zizibaloob/0c44bfe59b371b5ae0bd2edcb4a7e592

我會在這裏覆蓋的重要位。首先,FlexboxLayoutManagerMainActivity.onCreate()設置:

FlexboxLayoutManager manager = new FlexboxLayoutManager(this, FlexDirection.ROW); 
manager.setJustifyContent(JustifyContent.CENTER); 

RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler); 
recycler.setLayoutManager(manager); 

當我們創建佈局管理器,我們通過FlexDirection.ROW告訴它我們希望它出水平放置我們的項目(即填補了行,然後流到下一個行,而不是填滿一列,然後流向下一列)。

然後,我們使用JustifyContent.CENTER致電setJustifyContent()告訴經理我們希望部分填充的行以居中。

第二個重要的位是我們模仿GridView行爲的方式以及它具有一定數量的列的能力。此代碼是MyAdapter.onCreateViewHolder():這裏

ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) itemView.getLayoutParams(); 
layoutParams.width = (parent.getWidth()/4) - layoutParams.leftMargin - layoutParams.rightMargin; 
itemView.setLayoutParams(layoutParams); 

的關鍵是(parent.getWidth()/4),這給每個項目視圖可用寬度的四分之一。如果你想有一個不同的列數,只是改變48

我們也從寬度減去leftMarginrightMargin因爲我們的項目視圖具有裕度,我們需要留出空間爲它們。如果你的觀點不會有利潤率,你可以跳過這個。

把它放在一起,你會得到一個應用程序看起來像這樣:

enter image description here enter image description here

+0

真棒。謝謝! – lostintranslation

0

容易和更好的方式來排列圖片和內容的中心是利用重力在你item_layout文件中心,不在您的網格視圖的父級。

+0

當然,這會將項目中的內容居中,但不會將網格視圖中最後或奇數項目居中。 @BenP答案顯示了僅靠重力無法實現的解決方案。 – lostintranslation

+0

還要添加textview寬度以匹配parent和textAlignment屬性以居中。 – ShockWave