RecyclerView GridLayoutManager: how to auto-detect span count?

后端 未结 13 588
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 18:45

Using the new GridLayoutManager: https://developer.android.com/reference/android/support/v7/widget/GridLayoutManager.html

It takes an explicit span count, so the pro

13条回答
  •  無奈伤痛
    2020-11-28 18:49

    To accommodate orientation change on s-marks's answer, I added a check on width change (width from getWidth(), not column width).

    private boolean mWidthChanged = true;
    private int mWidth;
    
    
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
    {
        int width = getWidth();
        int height = getHeight();
    
        if (width != mWidth) {
            mWidthChanged = true;
            mWidth = width;
        }
    
        if (mColumnWidthChanged && mColumnWidth > 0 && width > 0 && height > 0
                || mWidthChanged)
        {
            int totalSpace;
            if (getOrientation() == VERTICAL)
            {
                totalSpace = width - getPaddingRight() - getPaddingLeft();
            }
            else
            {
                totalSpace = height - getPaddingTop() - getPaddingBottom();
            }
            int spanCount = Math.max(1, totalSpace / mColumnWidth);
            setSpanCount(spanCount);
            mColumnWidthChanged = false;
            mWidthChanged = false;
        }
        super.onLayoutChildren(recycler, state);
    }
    

提交回复
热议问题