今天發(fā)現(xiàn)給RecyclerView設(shè)置height為"wrap_content"并沒有生效腊尚,發(fā)現(xiàn)是官方的bug喜每。
雖然在23的包上進(jìn)行了修復(fù)间护。但在之前的版本都有這個(gè)問題企蹭。網(wǎng)上的方法一是在初始化時(shí)數(shù)組越界的崩潰白筹,二是只顯示第一行。
現(xiàn)在修改了一下谅摄,對(duì)每一行都進(jìn)行測(cè)量徒河,再把結(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);
}
}