ScrollView嵌套RecyclerView时,android:layout_height=”wrap_content”并不起作用,RecyclerView会填充剩余的整个屏幕空间,也就相当于android:layout_height=”match_parent”,通过重写GridLayoutManager或LinearLayoutManager 的onMeasure方法进行可重置RecyclerView的高度。
这里只给出GridLayoutManager的例子,LinearLayoutManager类似
a.设置LayoutManager
rvPhotos.setLayoutManager(new PhotoLayoutManage(this, 3));
b.RecyclerView的Adapter
Adapter中定义变量item中的height
private int itemHeight;
public int getItemHeight(){ return itemHeight;}
在Adapter的ViewHolder构造方法中设置item项显示后的高度
itemView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
itemHeight=convertView.getMeasuredHeight();
return true;
}
});
c.自定义GridLayoutManager重写onMeasure方法
public class PhotoLayoutManage extends GridLayoutManager{
// RecyclerView高度随Item自适应
public PhotoLayoutManage(Context context,int spanCount) {
super(context,spanCount);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, final int widthSpec,final int heightSpec) {
try {
//不能使用 View view = recycler.getViewForPosition(0);
//measureChild(view, widthSpec, heightSpec);
// int measuredHeight view.getMeasuredHeight(); 这个高度不准确
if(adapter!=null&&adapter.getItemHeight()>0) {
int measuredWidth = View.MeasureSpec.getSize(widthSpec);
int line = adapter.getItemCount() / getSpanCount();
if (adapter.getItemCount() % getSpanCount() > 0) line++;
int measuredHeight = adapter.getItemHeight()* line+rvPhotos.getPaddingBottom()+rvPhotos.getPaddingTop();
setMeasuredDimension(measuredWidth, measuredHeight);
}else{
super.onMeasure(recycler,state,widthSpec,heightSpec);
}
}catch (Exception e){
super.onMeasure(recycler,state,widthSpec,heightSpec);
}
}
}