RecyclerView GridLayoutManager: how to auto-detect span count?

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

    I extended the RecyclerView and overrode the onMeasure method.

    I set an item width(member variable) as early as I can,with a default of 1. This also updates on configuration changed. This will now have as many rows as can fit in portrait,landscape,phone/tablet etc.

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        super.onMeasure(widthSpec, heightSpec);
        int width = MeasureSpec.getSize(widthSpec);
        if(width != 0){
            int spans = width / mItemWidth;
            if(spans > 0){
                mLayoutManager.setSpanCount(spans);
            }
        }
    }
    

提交回复
热议问题