动态调整gridView的大小

时间:2016-10-11 11:18:58

标签: android android-layout gridview android-view

几个月前,我成功编写了代码来调整gridView的大小以适应每次加载新数据表时所需的行数。我刚刚注意到这已不再有效了,我不明白为什么。据我所知,所有改变的是我已经升级了SDK。下面是用于动态调整gridView大小的代码。

/**
 * create a resizable gridView by utilizing the onLayoutChanged system method
 * @param items an arrayList containing the items to be read into each cell
 */
public void createGridView(ArrayList<String> items)
{
    Log.d(TAG, "createGridView(): ");
    gridView.setAdapter(new GridAdapter(items));
    gridView.addOnLayoutChangeListener(new View.OnLayoutChangeListener(){

        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            Log.d(TAG, "onLayoutChange(): ");
            currentGridHeight = gridView.getHeight();
            if (singleGridHeight == 0){
                singleGridHeight = currentGridHeight/currentGridRows;
            }
            // fix for nestedScrollView automatically scrolling to the bottom after swipe
            nestedScrollView.scrollTo(0, 0);
        }
    });
}

/**
 * re-sizes the height of the gridView based on the amount of rows to be added
 * @param gridView
 * @param items
 * @param columns
 */
private static void resizeGridView(GridView gridView, int items, int columns) {
    Log.d(TAG, "resizeGridView(): ");
    ViewGroup.LayoutParams params = gridView.getLayoutParams();
    params.height = singleGridHeight * items;
    gridView.setLayoutParams(params);
    gridView.requestLayout();
}

// gridView adapter
private static final class GridAdapter extends BaseAdapter {
    final ArrayList<String> mItems;
    final int mCount;

    /**
     * Default constructor
     *
     * @param items to fill data to
     */
    private GridAdapter(final ArrayList<String> items) {
       // create arrayList full of data called "items"
        // ..
        // ..

        // resizing the gridView based on the number of rows
        currentGridRows = items.size();
// if this isn't the very first gridView then resize it to fit the rows
        if (currentGridHeight != 0){
            resizeGridView(gridView,items.size(),6);
        }
    }

首次创建gridView时(第一个表格已加载),我得到了gridView高度的测量值,并将其除以行数,以确定每行所需的高度。当我加载后续的gridViews时,我通过将此高度乘以行数来调整它们的大小。

这已不再适用。后续的gridViews仍大致只能容纳一行。

有什么想法吗?

编辑:看起来它正在计算singleRowHeight为9dp,而实际上每行需要大约64dp。

1 个答案:

答案 0 :(得分:2)

尝试将RecyclerViewLayoutManager一起使用,如下所示:

recyclerView.setLayoutManager(new GridLayoutManager(context, columnsCount));
相关问题