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