GridLayoutManager - how to auto fit columns?

后端 未结 8 2030
野性不改
野性不改 2020-11-30 18:30

I have a RecyclerView with a GridLayoutManager that displays Card Views. I want the cards to rearrange according to the screen size (the Google Play app does this kind of th

8条回答
  •  萌比男神i
    2020-11-30 19:11

    public class AutoFitGridLayoutManager extends GridLayoutManager {
    
    private int columnWidth;
    private boolean columnWidthChanged = true;
    
    public AutoFitGridLayoutManager(Context context, int columnWidth) {
        super(context, 1);
    
        setColumnWidth(columnWidth);
    }
    
    
    public void setColumnWidth(int newColumnWidth) {
        if (newColumnWidth > 0 && newColumnWidth != columnWidth) {
            columnWidth = newColumnWidth;
            columnWidthChanged = true;
        }
    }
    
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (columnWidthChanged && columnWidth > 0) {
            int totalSpace;
            if (getOrientation() == VERTICAL) {
                totalSpace = getWidth() - getPaddingRight() - getPaddingLeft();
            } else {
                totalSpace = getHeight() - getPaddingTop() - getPaddingBottom();
            }
            int spanCount = Math.max(1, totalSpace / columnWidth);
            setSpanCount(spanCount);
            columnWidthChanged = false;
        }
        super.onLayoutChildren(recycler, state);
    }
    

    }

    now you can set LayoutManager to recycle view

    here i have set 250px

     AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 250);
     recycleView.setLayoutManager(layoutManager)
    

    show the belove image

提交回复
热议问题