【问题标题】:how to dynamically change the gridview rows and columns in Android如何在Android中动态更改gridview的行和列
【发布时间】:2015-05-18 15:24:17
【问题描述】:

我在我的活动中使用 Gridview。我还有一个 CustomGridAdpater 来显示每个网格上的图像和文本视图。

在启动我的活动时。我需要根据值动态创建网格行和列。

count = 4   2x2 grid
count = 9   3x3 grid
count = 16  4x4 grid

请告诉我如何实现此功能。

我的网格视图:

 <GridView
        android:id="@+id/Favorite_GridView"
        android:layout_width="wrap_content"
        android:layout_height="300dp"
        android:layout_marginTop="10dp"
        android:layout_below="@id/Date_RelativeLayout"           
        android:listSelector="@drawable/gridview_norecode_selector"
        android:numColumns="auto_fit"                  />

我已将列设为 android:numColumns="auto_fit" 所以它默认为 2 列。

我也有一个自定义 GridAdapter

    <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/grid_color_selector" >
<ImageView
    android:id="@+id/image"
   android:layout_width="100dp"
    android:layout_height="100dp"
   android:layout_marginRight="10dp"
   />        
<TextView
    android:id="@+id/Day_TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/gridview_line_norecord"
    android:gravity="center"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:text="Hello" />

我也在我的活动中使用了这个功能

  if(newList.length > 4)
    {
        mgridView.setColumnWidth(350);

    }

但我担心在活动中手动赋值。我觉得横向模式可能会给 UI 异常。

请帮助我如何进行。

【问题讨论】:

  • 你试过RecyclerViewGridLayoutManager吗?

标签: android gridview


【解决方案1】:

hoomi 的评论是对的。

使用 RecyclerView 和 GridLayoutManager。! 在.xml中

<android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:numColumns="2"
            android:horizontalSpacing="@dimen/gridview_horizontal_spacing"
            android:verticalSpacing="@dimen/gridview_vertical_spacing"
            android:id="@+id/recyclerView" />

recyclerView.setLayoutManager(new GridLayoutManager(context , number));

gridview.setNumColumns(number);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多