[Android開發(fā)]RecyclerView的"wrap_content" 無效問題

今天發(fā)現(xiàn)給RecyclerView設(shè)置height為"wrap_content"并沒有生效,發(fā)現(xiàn)是官方的bug。
雖然在23的包上進(jìn)行了修復(fù)。但在之前的版本都有這個問題。網(wǎng)上的方法一是在初始化時數(shù)組越界的崩潰,二是只顯示第一行。
現(xiàn)在修改了一下,對每一行都進(jìn)行測量,再把結(jié)果匯總再setMeasuredDimension。這樣才能完全的顯示所有行數(shù)。

public class WrapLinearLayoutManager extends LinearLayoutManager {

    public WrapLinearLayoutManager(Context context) {
        super(context);
    }

    public WrapLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        int itemCount = state.getItemCount();
        if(itemCount == 0) {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
            return ;
        }
        int holdMeasuredHeight = 0;
        int holdMeasuredWidth = 0;
        if(VERTICAL == getOrientation()){
            for(int i = itemCount-1; i>=0;i--){
                View view = recycler.getViewForPosition(i);
                if(view != null){
                    measureChild(view, widthSpec, heightSpec);
                    holdMeasuredHeight += view.getMeasuredHeight();

                }
            }
            holdMeasuredWidth = View.MeasureSpec.getSize(widthSpec);
        }else {
            int maxHeight=0;
            for(int i = itemCount-1; i>=0;i--){
                View view = recycler.getViewForPosition(i);
                if(view != null){
                    measureChild(view, widthSpec, heightSpec);
                    holdMeasuredWidth += view.getMeasuredWidth();
                    if(maxHeight<view.getMeasuredHeight())maxHeight=view.getMeasuredHeight();
                }
            }
            if(holdMeasuredWidth > View.MeasureSpec.getSize(widthSpec)){
                holdMeasuredWidth = View.MeasureSpec.getSize(widthSpec);
            }
            holdMeasuredHeight = View.MeasureSpec.getSize(heightSpec);
            if(maxHeight !=0 && maxHeight < holdMeasuredHeight){
                holdMeasuredHeight = maxHeight;
            }
        }
        setMeasuredDimension(holdMeasuredWidth, holdMeasuredHeight);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容