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

相关问题