2

繼續此問題Layout dynamic grid in middle根據單元格數量的可變寬度GridView

我有一個網格。它有不同的寬度,取決於用戶的操作。有時可能是4 * 3其他時間2 * 5

寬度也可能大於4。

我的問題是,網格本身總是相同的寬度和細胞伸展來填補它。這意味着2 * 5的單元寬度是4 * 3單元寬度的兩倍。理想情況下,我希望網格寬度可以調整。它應該是columnWidth * numOfColumns。

我的xml下面的寬度是175px,我認爲這是造成這種情況的原因。當我使用wrap_content時,它佔用整個屏幕寬度並忽略我的兩個填充視圖。

任何人都可以幫忙嗎? 謝謝

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:gravity="center" 
     android:background="#C8C8C8" 
     android:orientation="horizontal"> 

    <View 
      android:background="#C8C8C8" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="2"/> 

    <GridView xmlns:android="http://schemas.android.com/apk/res/android" 
       android:id="@+id/grid_view" 
       android:background="#FF000000" 
       android:layout_width="175px" 
       android:layout_height="wrap_content" 
       android:numColumns="5" 
       android:columnWidth="35dp" 
       android:verticalSpacing="1dp" 
       android:horizontalSpacing="1dp" 
      /> 
    <!--android:layout_width="wrap_content"--> 

    <View 
      android:background="#FFC8C8C8" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="2"/> 
</LinearLayout> 

澄清什麼林後多一點。

上半部分包含一個應該理想居中的網格。 單元應該具有相同的寬度(並且理想情況下相同高度,所以是正方形) 上面的LinearLayout下有一個列表,如果網格佔用太多空間(但絕不應占用超過50%的屏幕)

enter image description here

+0

*這應該只是columnWidth中X numOfColumns * - 但你有什麼樣的價值考慮的列寬? – Luksprog

+0

我正在考慮每寬度30-50dp – RNJ

+0

你不能直接在佈局中做到這一點,你需要一個來計算這些值並手動設置它們。我將使用自定義ViewGroup來保存GridView和ListView,並在自定義ViewGroup中計算確切的值。 – Luksprog

回答

1

您需要設置grid_view的寬度wrap_contentcenter_horizontal = "true",不是使適配器,並設置單元格的寬度和高度爲固定值getView()方法(從DP計算),之後,當你將改變您的代碼中的單元格數 - 網格視圖會將其寬度更改爲適合單元格數量*每個單元格的寬度

//cellWidth = width of each cell including paddings 
//gridRowsNumber = number of cells in width 
//gridColsNumber = number of cells in height 
// in activity's of fragment's onCreate(); 
gridView.getLayoutParams().width = cellWidth * gridRowsNumber; 
gridView.getLayoutParams().height = cellWidth * gridColsNumber; 
佈局

<GridView 
    android:id="@+id/grid_view" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:background="@android:color/white" 
    android:numColumns="5" 
    android:scrollbars="none"> 
</GridView> 
適配器

public View getView (int position, View convertView, ViewGroup parent) 
{ 
    ... 
    holder.cellView.getLayoutParams().height = cellWidth; 
    holder.cellView.getLayoutParams().width = cellWidth; 
    ... 
} 
+0

太好了。效果很好。謝謝! – RNJ

相關問題