Changing number of columns in RecyclerView gridlayout

后端 未结 4 806
梦如初夏
梦如初夏 2020-12-08 16:44

I am trying to change the number of columns that appear in the recycler view (grid layout) based on the display size. However I couldn\'t figure out a proper way of achievin

4条回答
  •  一向
    一向 (楼主)
    2020-12-08 16:59

    public class VarColumnGridLayoutManager extends GridLayoutManager {
    
    private int minItemWidth;
    
    public VarColumnGridLayoutManager(Context context, int minItemWidth) {
        super(context, 1);
        this.minItemWidth = minItemWidth;
    }
    
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler,
            RecyclerView.State state) {
        updateSpanCount();
        super.onLayoutChildren(recycler, state);
    }
    
    private void updateSpanCount() {
        int spanCount = getWidth() / minItemWidth;
        if (spanCount < 1) {
            spanCount = 1;
        }
        this.setSpanCount(spanCount);
    }}
    

提交回复
热议问题