ItemDecoration解析(三) 实现stickyHeader效果

前两篇介绍完了ItemDecoration的基本用法。这次打算用ItemDecoration做点好玩的——实现stickyHeader效果。如图:

《ItemDecoration解析(三) 实现stickyHeader效果》

我们从动画可以看出,其实头部有种,一种跟ItemView在同一层级,类似一个不同typeItem;另外一个始终保持在最上层,并且滑动到每组的最后一个item时,会有一个被顶上去,或者被拉下来的效果。

我们继续分析下,应该如何实现:

  1. itemView同一层级的header,我们可以把它当做是一个divider,通过getItemOffsetsonDraw来处理,且每组第一个Item的上方才显示。

  2. 浮在itemView上层的header,很明显可以通过onDrawOver来实现。

  3. 浮在itemView上层的header被顶上去和被拉下来的效果,只需要当每组最后一个Itembottom小于headerheight时,让header跟随这个item就行,换句话说就是此时让headerbottom等于firstItembottom。(有点绕的话,结合下面的图看看)

    《ItemDecoration解析(三) 实现stickyHeader效果》

还有最后一个问题需要确认,那就是哪个item是每组的开始,哪个Item是每组的结束。 这个问题跟我们能拿到的数据集合有关。有可能拿到的是类似IOS那样:titleList<A>集合,Item是分好组的List<List<B>>集合(IOS的小伙伴说的,应该没骗我,indexPath我听过);也有可能拿到就是一个List<B>集合,泛型 B有个字段作为titletitle相同便是同一分组。总之不管数据集合是怎么样的,我们都需要确认那个item是每组的开始,哪个item是每组的结束。假定我们拿到的就是一个List<B>形式的集合,item的实体类如下:

public class AppInfoBean {
    public String name;
    public String url;
    public String tag;

    public AppInfoBean(String name, String url,String tag) {
        this.name = name;
        this.url = url;
        this.tag = tag;
    }
}

具体应该如何判断呢,首先,position为0肯定是第一组的开始;positionList.size()-1 肯定是最后一组的结束;其他position,如果当前的tag与上一个positiontag不等,那么肯定是某组的开始,如果当前的tag与下一个positiontag不等,那么肯定是某组的结束。定义一个类来描述每个Item的开始,结束状态:

public class SectionBean {
    public boolean isGroupStart;
    public boolean isGroupEnd;
}

上面的分析,可以总结成如下代码:

    SectionBean tag;
    if (position == 0) {
        tag.isGroupStart = true;
        tag.isGroupEnd = !mDatas.get(position).tag.equals(mDatas.get(position + 1).tag);
    } else if (position == mDatas.size() - 1) {
        tag.isGroupStart = !mDatas.get(position).tag.equals(mDatas.get(position - 1).tag);
        tag.isGroupEnd = true;
    } else {
        tag.isGroupStart = !mDatas.get(position).tag.equals(mDatas.get(position - 1).tag);
        tag.isGroupEnd = !mDatas.get(position).tag.equals(mDatas.get(position + 1).tag);
    }

至于这个判断放在什么地方,就看大家的见解了。我这里选择在adapteronBindViewHolder中生成每个position对应的SectionBean,通过itemviewsetTag方法存起来,这样的话,在ItemDecoration可以通过getTag取出来,具体代码如下:(当然直接在ItemDecoration中做判断也可以)

    @Override
    public void onBindViewHolder(StickHeaderVH holder, int position) {
        holder.sdvPic.setImageURI(mDatas.get(position).url);
        holder.tvTitle.setText(mDatas.get(position).name);
        generateTag(holder, position);

    }

    private void generateTag(StickHeaderVH holder, int position) {
        SectionBean tag;
        // 没有tag的话 new 一个, 有的话 复用
        if (holder.itemView.getTag() == null) {
            tag = new SectionBean();
        } else {
            tag = (SectionBean) holder.itemView.getTag();
        }
        // 判断当前position的开始结束状态
        if (position == 0) {
            tag.isGroupStart = true;
            tag.isGroupEnd = !mDatas.get(position).tag.equals(mDatas.get(position + 1).tag);
        } else if (position == mDatas.size() - 1) {
            tag.isGroupStart = !mDatas.get(position).tag.equals(mDatas.get(position - 1).tag);
            tag.isGroupEnd = true;
        } else {
            tag.isGroupStart = !mDatas.get(position).tag.equals(mDatas.get(position - 1).tag);
            tag.isGroupEnd = !mDatas.get(position).tag.equals(mDatas.get(position + 1).tag);
        }
        holder.itemView.setTag(tag);
    }

经过最开始的分析,与ItemView同一层级的header其实就是一个有文字的divider,只有每组的第一个Item才显示,这个很好处理,代码如下(文字居中的处理其实有很多细节可以抠的,有机会单独列出):

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 如果是头部
        if (((SectionBean) view.getTag()).isGroupStart) {
            outRect.set(0, (int) mDividerHeight, 0, 0);
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            // 如果是头
            if (position != RecyclerView.NO_POSITION
                    && ((SectionBean) view.getTag()).isGroupStart) {
                drawHeader(c, parent, view, position);
            }
        }
    }

    /**
     * 画头部
     *
     * @param c
     * @param parent
     * @param view
     * @param position
     */
    private void drawHeader(Canvas c, RecyclerView parent, View view, int position) {
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();
        int bottoom = view.getTop() - params.topMargin - Math.round(ViewCompat.getTranslationY(view));
        int top = (int) (bottoom - mDividerHeight);
        // 计算文字居中时候的基线
        Rect targetRect = new Rect(left, top, right, bottoom);
        Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
        int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
        c.drawRect(left, top, right, bottoom, mPaint);
        c.drawText(mDatas.get(position).tag, left, baseline, mTextPaint);
    }

接下来再处理浮在顶层的header,上面已经分析过了,这个header一般情况下都是固定在recyclerView的顶部,只有达到临界点后,其底部才会跟随第一个可见ItemView的底部,所以我们只需要着重留意下临界点就行了,代码如下:

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        View view = parent.getChildAt(0);
        View view2 = parent.getChildAt(1);
        if (view != null && view2 != null) {
            SectionBean section1 = (SectionBean) view.getTag();
            SectionBean section2 = (SectionBean) view2.getTag();

            int position = parent.getChildAdapterPosition(view);
            final int left = parent.getPaddingLeft();
            final int right = parent.getWidth() - parent.getPaddingRight();
            int bottoom = (int) mDividerHeight;
            int top = 0;
            // 判断是否达到临界点
            // (第一个可见item是每组的最后一个,第二个可见tiem是下一组的第一个,并且第一个可见item的底部小于header的高度)
            // 这里直接判断item的底部位置小于header的高度有点欠妥,应该还要考虑paddingtop以及margintop,这里展示不考虑了
            if (section1.isGroupEnd && section2.isGroupStart && view.getBottom() <= mDividerHeight) {
                bottoom = view.getBottom();
                top = (int) (bottoom - mDividerHeight);
            }
            // 计算文字居中时候的基线
            Rect targetRect = new Rect(left, top, right, bottoom);
            Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
            int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
            // 背景
            c.drawRect(left, top, right, bottoom, mPaint);
            // 文字
            c.drawText(mDatas.get(position).tag, left, baseline, mTextPaint);
        }
    }

这样基本上就OK了, 唯一的遗憾就是header不能点击啊。。。。源码点我

    原文作者:static_sadhu
    原文地址: https://www.jianshu.com/p/3221b5c8fc38
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞