RecyclerView利用ItemDecoration实现头部悬停效果【类似微信通讯录效果】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaxiazaizai01/article/details/62430432

对于RecyclerView的ItemDecoration相信大家都不会陌生,因为RecyclerView并不像ListView那样自带分割线,所以我们需要继承ItemDecoration去手动绘制分割线。本篇文章主要是利用ItemDecoration的特性来绘制实现悬浮效果,就像微信中的通讯录一样,只不过微信的通讯录没有悬停而已。

没有效果图,光bb是不具有说服力的,下面我们来看下效果图
这里写图片描述

ItemDecoration中的几个关键方法介绍

(1)getItemOffsets()

(2)onDraw()

(3)onDrawOver()

说明:在解释上面的几个重要的方法之前,我们先来看一张图
这里写图片描述
这里非常感谢Piasy大牛提供的图片,原文地址:https://blog.piasy.com/2016/03/26/Insight-Android-RecyclerView-ItemDecoration/?utm_source=tuicool&utm_medium=referral

由上面的效果图可以看出来,通过设置RecyclerView的item的不同方向的padding值,可以让我们的item空出不同方向的距离,我们就可以利用空出的距离来绘制我们的悬浮栏了。为什么说是padding值呢?我们大体说一下,查看官方DividerItemDecoration源码,不能翻墙了,借用上图作者文章中的一段代码

@Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }

我们看到了,以其中一种情况分析,当我们的item是垂直排列的时候,outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());下方空出来的是mDivider.getIntrinsicHeight()高度的距离。在RecyclerView源代码中找到调用getItemOffsets()的方法,即:getItemDecorInsetsForChild(View child)方法

Rect getItemDecorInsetsForChild(View child) {
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        if (!lp.mInsetsDirty) {
            return lp.mDecorInsets;
        }

        if (mState.isPreLayout() && (lp.isItemChanged() || lp.isViewInvalid())) {
            // changed/invalid items should not be updated until they are rebound.
            return lp.mDecorInsets;
        }
        final Rect insets = lp.mDecorInsets;
        insets.set(0, 0, 0, 0);
        final int decorCount = mItemDecorations.size();
        for (int i = 0; i < decorCount; i++) {
            mTempRect.set(0, 0, 0, 0);
            mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
            insets.left += mTempRect.left;
            insets.top += mTempRect.top;
            insets.right += mTempRect.right;
            insets.bottom += mTempRect.bottom;
        }
        lp.mInsetsDirty = false;
        return insets;
    }

我们看到,outRect.set(left, top, right, bottom)的值放到了Rect对象的insets 变量中,然后我们再继续查找这个insets,如何查找,我们需要看看谁调用了 getItemDecorInsetsForChild(View child) 方法。在RecyclerView源码中继续搜索,定位到measureChild(View child, int widthUsed, int heightUsed)方法

/**
         * Measure a child view using standard measurement policy, taking the padding
         * of the parent RecyclerView and any added item decorations into account.
         *
         * <p>If the RecyclerView can be scrolled in either dimension the caller may
         * pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
         *
         * @param child Child view to measure
         * @param widthUsed Width in pixels currently consumed by other views, if relevant
         * @param heightUsed Height in pixels currently consumed by other views, if relevant
         */
        public void measureChild(View child, int widthUsed, int heightUsed) {
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();

            final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
            widthUsed += insets.left + insets.right;
            heightUsed += insets.top + insets.bottom;
            final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
                    getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
                    canScrollHorizontally());
            final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
                    getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
                    canScrollVertically());
            if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
                child.measure(widthSpec, heightSpec);
            }
        }

现在就清晰了,在测量子item的宽高时,原来存到insets中的left、right、top、bottom分别加到了对应的padding值中去了,getChildMeasureSpec(getWidth(), getWidthMode(),getPaddingLeft() +getPaddingRight() + widthUsed, lp.width,canScrollHorizontally());

说了这么多就是为了分析getItemOffsets()方法的作用,就是通过设置RecyclerView的item的上下左右padding值,来预留出空间,通过上面的图片加之源码的分析,我们理解起来就更加容易了。

既然已经预留了item的paddingTop的距离了,那么我们就需要用到第二个方法onDraw()去绘制我们要显示的内容。由效果图可以看出我们要绘制的就是一个矩形条以及文字,所以接下来的工作就又回归到我们熟悉的自定义view上面了。首先我们要先new出来画笔,getItemOffsets()方法中具体该预留多高的空间?其实就是矩形条的高度,分析完了,接下来看这两个方法中的代码逻辑

@Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        //通过查看源码可知道获取position的方法
        int position = ((RecyclerView.LayoutParams)view.getLayoutParams()).getViewLayoutPosition();
        if(position > -1){
            if(position == 0){
                //默认第一个位置,肯定是要设置悬浮栏的,这里只需要上边top留出空间即可
                outRect.set(0, titleHeight, 0, 0);//里面参数表示:左上右下的内边距padding距离
            }else{
                //继续分情况判断,当滑动到某一个item时(position位置)得到tag标签,与上一个item对应的标签不一致( position-1 位置),说明这是下一分组了
                if(lists.get(position).getTag() != null && !lists.get(position).getTag().equals(lists.get(position-1).getTag())){
                    //说明这是下一组了,需要留出空间好去绘制悬浮栏用
                    outRect.set(0, titleHeight, 0, 0);
                }else{
                    //标签相同说明是同一组的数据,比如都是 A 组下面的数据,那么就不需要再留出空间绘制悬浮栏了,共用同一个 A 组即可
                    outRect.set(0, 0, 0, 0);
                }
            }
        }
    }

说明一点:我们该通过具体哪种方法获得position相应的位置呢?不知道的话就可以点进去查看源代码中是如何处理的

public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
            getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
                    parent);
        }

其中:
/**
         * Returns the adapter position that the view this LayoutParams is attached to corresponds
         * to as of latest layout calculation.
         *
         * @return the adapter position this view as of latest layout pass
         */
        public int getViewLayoutPosition() {
            return mViewHolder.getLayoutPosition();
        }

接着,我们继续看我们的onDraw()方法

@Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        //先画出带有背景颜色的矩形条悬浮栏,从哪个位置开始绘制到哪个位置结束,则需要先确定位置,再画文字(即:title)
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        //父view(RecyclerView)有padding值,子view有margin值
        int childCount = parent.getChildCount();//得到的数据其实是一屏可见的item数量并非总item数,再复用
        for(int i = 0; i < childCount; i++){
            View child = parent.getChildAt(i);
            //子view(即:item)有可能设置有margin值,所以需要parms来设置margin值。 
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            //以及 获取 position 位置
            int position = params.getViewLayoutPosition();
            if(position > -1){
                if(position == 0){//肯定是要绘制一个悬浮栏 以及 悬浮栏内的文字
                    //画矩形悬浮条以及文字
                    drawRectAndText(c, left, right, child, params, position);
                }else{
                    if(lists.get(position).getTag() != null && !lists.get(position).getTag().equals(lists.get(position - 1).getTag())){
                        //和上一个Tag不一样,说明是另一个新的分组
                        //画矩形悬浮条以及文字
                        drawRectAndText(c, left, right, child, params, position);
                    }else{
                        //说明是一组的,什么也不画,共用同一个Tag
                    }
                }
            }

        }
    }

这样,我们就实现了简单的微信中的通讯录效果,在调试过程中,我们可以发现:当我们在getItemOffsets()方法中通过outRect.set(0, titleHeight, 0, 0)为我们的onDraw()中绘制矩形条预留空间,假如我们预留的空间小于我们要绘制的实际高度时,也就是说我们在getItemOffsets()方法中预留了20dp的paddingTop距离,而我们实际在onDraw()中绘制的矩形高度时30dp,那么又将出现什么现象呢?先看效果图

这里写图片描述

我们看到绘制的灰色的矩形条超出getItemOffsets()为我们预留的空间时,就会被item遮盖,但是会有残影,如上图所示。有童鞋该说了,为什么顶部的A矩形条没有,那是因为我重写了另一个方法,也就是我们接下啦要介绍的onDrawOver()方法。出现这个的原因是因为ItemDecoration的onDraw()方法比View(RecyclerView)的onDraw()先执行,也就是说,ItemDecoration的onDraw()绘制的内容处于最底层。ItemDecoration的onDraw()方法为什么会先于View的onDraw()方法执行?我们可以查看源代码,由于篇幅原因,这里就不再分析了。

接下来,我们分析最后一个方法:onDrawOver()方法

从上面分析被遮盖的图片中,我们看到为什么A所在的矩形条没有没item遮盖住呢?因为我们在onDrawOver()方法中绘制了一个靠顶的矩形条,onDrawOver()方法自带悬浮特性。也就是说,这里的A所在的矩形条是在item的上层的。从而可以看出onDrawOver()方法是最后才执行的(当然了,执行的顺序还是需要查看源代码的!!!),简单说下这几个执行的顺序:getItemOffsets()方法—>ItemDecoration的onDraw()方法—>View的onDraw()方法绘制item的view—>ItemDecoration的onDrawOver()方法。

@Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        //其实就是获取到每一个可见的位置的item时,执行画顶层悬浮栏
        int firstPosition = ((LinearLayoutManager)parent.getLayoutManager()).findFirstVisibleItemPosition();
    //    View child = parent.getChildAt(firstPosition);
        View child = parent.findViewHolderForLayoutPosition(firstPosition).itemView;
        //绘制悬浮栏,其实这里和上面onDraw()绘制方法差不多,只不过,这里面的绘制是在最上层,会悬浮
        paint.setColor(Color.parseColor("#FFDFDFDF"));
        c.drawRect(parent.getPaddingLeft(), parent.getPaddingTop(), parent.getRight() - parent.getPaddingRight(), parent.getPaddingTop() + titleHeight, paint);
        //绘制文字
        paint.setColor(Color.parseColor("#88888888"));
        paint.getTextBounds(lists.get(firstPosition).getTag(), 0, lists.get(firstPosition).getTag().length(), rectBounds);
        c.drawText(lists.get(firstPosition).getTag(), child.getPaddingLeft(), parent.getPaddingTop() + titleHeight - (titleHeight/2 - rectBounds.height()/2), paint);
    }

上述代码中,我们可以看到item是不是需要预留空间,需要根据tag标记来决定。这个tag标记是我们定义在实体类中的一个字段,作用就是为了根据此标记将具有同一此标记的数据分到同一组中。

接下来看下我们的实体类

/**
 *  实体类
 */

public class CategoryBean implements Serializable{
    private static final long serialVersionUID = 5136218664701666396L;

    private String tag;//所属的分类
    private String categoryName;

    public CategoryBean(String tag, String categoryName) {
        this.tag = tag;
        this.categoryName = categoryName;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
}

adapter适配器

/**
 *  适配器
 */

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder>{

    private Context context;
    private List<CategoryBean> lists;
    private LayoutInflater inflater;

    public CategoryAdapter(Context context, List<CategoryBean> lists) {
        this.context = context;
        this.lists = lists;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_category, parent, false);
        CategoryViewHolder holder = new CategoryViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(CategoryViewHolder holder, final int position) {
        CategoryBean bean = lists.get(position);
        holder.tvName.setText(bean.getCategoryName());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "点击了的位置position= "+ position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return null !=lists ?lists.size() : 0;
    }

    public static class CategoryViewHolder extends RecyclerView.ViewHolder{

        TextView tvName;

        public CategoryViewHolder(View itemView) {
            super(itemView);
            tvName = (TextView) itemView.findViewById(R.id.tvName);
        }
    }
}

最后,我们看看如何去使用

public class MainActivity extends AppCompatActivity {

    private TitleItemDecoration titleItemDecoration;
    private RecyclerView recyclerView;
    private CategoryAdapter adapter;
    private List<CategoryBean> lists;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置测试数据
        setDatas();

        adapter = new CategoryAdapter(this, lists);
        recyclerView.setAdapter(adapter);
        titleItemDecoration = new TitleItemDecoration(this, lists);
        recyclerView.addItemDecoration(titleItemDecoration);

    }

    private void setDatas() {
        lists = new ArrayList<>();
        lists.add(new CategoryBean("A", "哎"));
        lists.add(new CategoryBean("A", "爱"));
        lists.add(new CategoryBean("A", "昂"));
        lists.add(new CategoryBean("B", "beautiful"));
        lists.add(new CategoryBean("B", "beak"));
        lists.add(new CategoryBean("B", "but"));
        lists.add(new CategoryBean("B", "bring"));
        lists.add(new CategoryBean("C", "category"));
        lists.add(new CategoryBean("C", "can"));
        lists.add(new CategoryBean("C", "captive"));
        lists.add(new CategoryBean("C", "computer"));
        lists.add(new CategoryBean("D", "default"));
    }
}

参考的牛人博客链接

张旭童 http://blog.csdn.net/zxt0601

Piasy https://blog.piasy.com/2016/03/26/Insight-Android-RecyclerView-ItemDecoration/?utm_source=tuicool&utm_medium=referral

站在牛人的肩膀上,我们将会更加轻松。非常感谢那些无私奉献的大牛们。当我们遇到一些解决不了或者没思路的问题时,要学会翻阅源码,或者官方的一些示例代码,会有意外的惊喜。最后不得不说,RecyclerView中相关的内容很多很强大。

希望能对你有所帮助,主要代码已经贴出来了,下班咯,源代码就不再上传了,如果有需要源码的请跟我说下

点击下载源码

猜你喜欢

转载自blog.csdn.net/xiaxiazaizai01/article/details/62430432
今日推荐