RecyclerView GridLayoutManager: how to auto-detect span count?

后端 未结 13 562
没有蜡笔的小新
没有蜡笔的小新 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 19:11

    Here's the relevant parts of a wrapper I've been using to auto-detect the span count. You initialize it by calling setGridLayoutManager with a R.layout.my_grid_item reference, and it figures out how many of those can fit on each row.

    public class AutoSpanRecyclerView extends RecyclerView {
        private int     m_gridMinSpans;
        private int     m_gridItemLayoutId;
        private LayoutRequester m_layoutRequester = new LayoutRequester();
    
        public void setGridLayoutManager( int orientation, int itemLayoutId, int minSpans ) {
            GridLayoutManager layoutManager = new GridLayoutManager( getContext(), 2, orientation, false );
            m_gridItemLayoutId = itemLayoutId;
            m_gridMinSpans = minSpans;
    
            setLayoutManager( layoutManager );
        }
    
        @Override
        protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
            super.onLayout( changed, left, top, right, bottom );
    
            if( changed ) {
                LayoutManager layoutManager = getLayoutManager();
                if( layoutManager instanceof GridLayoutManager ) {
                    final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
                    LayoutInflater inflater = LayoutInflater.from( getContext() );
                    View item = inflater.inflate( m_gridItemLayoutId, this, false );
                    int measureSpec = View.MeasureSpec.makeMeasureSpec( 0, View.MeasureSpec.UNSPECIFIED );
                    item.measure( measureSpec, measureSpec );
                    int itemWidth = item.getMeasuredWidth();
                    int recyclerViewWidth = getMeasuredWidth();
                    int spanCount = Math.max( m_gridMinSpans, recyclerViewWidth / itemWidth );
    
                    gridLayoutManager.setSpanCount( spanCount );
    
                    // if you call requestLayout() right here, you'll get ArrayIndexOutOfBoundsException when scrolling
                    post( m_layoutRequester );
                }
            }
        }
    
        private class LayoutRequester implements Runnable {
            @Override
            public void run() {
                requestLayout();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题