Changing number of columns in RecyclerView gridlayout

后端 未结 4 804
梦如初夏
梦如初夏 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 17:05

    If you provide a fixed column width, you can extend RecyclerView and set the span count in onMeasure accordingly:

    public AutofitRecyclerView(Context context, AttributeSet attrs) {
      super(context, attrs);
    
      if (attrs != null) {
        // Read android:columnWidth from xml
        int[] attrsArray = {
            android.R.attr.columnWidth
        };
        TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
        columnWidth = array.getDimensionPixelSize(0, -1);
        array.recycle();
      }
    
      manager = new GridLayoutManager(getContext(), 1);
      setLayoutManager(manager);
    }
    
    protected void onMeasure(int widthSpec, int heightSpec) {
      super.onMeasure(widthSpec, heightSpec);
      if (columnWidth > 0) {
        int spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
        manager.setSpanCount(spanCount);
      }
    }
    

    See my blog post for more info: http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html

提交回复
热议问题