Gridview height gets cut

后端 未结 6 1555
刺人心
刺人心 2020-11-22 17:26

I\'m trying to display 8 items inside a gridview. Sadly, the gridview height is always too little, so that it only shows the first row, and a little part of the second.

6条回答
  •  感动是毒
    2020-11-22 17:48

    Another similar approach that worked for me, is to calculate the height for one row and then with static data (you may adapt it to paginate) you can calculate how many rows you have and resize the GridView height easily.

        private void resizeGridView(GridView gridView, int items, int columns) {
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        int oneRowHeight = gridView.getHeight();
        int rows = (int) (items / columns);
        params.height = oneRowHeight * rows;
        gridView.setLayoutParams(params);
    }
    

    Use this code after setting the adapter and when the GridView is drawn or you will get height = 0.

    gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (!gridViewResized) {
                        gridViewResized = true;
                        resizeGridView(gridView, numItems, numColumns);
                    }
                }
            });
    

提交回复
热议问题