码迷,mamicode.com
首页 > 其他好文 > 详细

RecyclerView高度随Item自适应 GridLayoutManager和LinearLayoutManager都适用

时间:2015-08-13 15:56:16      阅读:671      评论:0      收藏:0      [点我收藏+]

标签:布局

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 measuredHeight = adapter.getItemHeight()+rvPhotos.getPaddingBottom()+rvPhotos.getPaddingTop();
                        int line = adapter.getItemCount() / getSpanCount();
                        if (adapter.getItemCount() % getSpanCount() > 0) line++;
                        setMeasuredDimension(measuredWidth, measuredHeight * line);
                    }else{
                        super.onMeasure(recycler,state,widthSpec,heightSpec);
                    }

            }catch (Exception e){
                super.onMeasure(recycler,state,widthSpec,heightSpec);
            }
        }
    }

版权声明:本文为博主原创文章,未经博主允许不得转载。

RecyclerView高度随Item自适应 GridLayoutManager和LinearLayoutManager都适用

标签:布局

原文地址:http://blog.csdn.net/xiaoluoli88/article/details/47612417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!