【问题标题】:Dynamically resizing a gridView动态调整gridView的大小
【发布时间】:2016-10-11 11:18:58
【问题描述】:

几个月前,我成功编写了代码来调整 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。

【问题讨论】:

    标签: android android-layout gridview android-view


    【解决方案1】:

    尝试像这样使用RecyclerViewLayoutManager

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

    【讨论】:

    • 对 gridView 有什么建议吗?
    • 每行大约需要 64dp:可能是您的 ViewGroup 或其中的元素有问题。您能否使用用于 GridView 项目的布局更新您的问题。并且在你改变你的身高后尝试notifyDataSetChangednotifyItemChanged(int position)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2012-10-24
    • 2014-03-19
    • 2015-11-02
    • 2023-03-14
    相关资源
    最近更新 更多