recyclerView 吸顶式效果

学习参考网站原文作者他是采用Bundle的方式,每个item都是new这样耗费内存,我自己优化了下。界面也改了

GIF.gif

核心代码:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                View view = recyclerView.findChildViewUnder(0, 0);
                if (view == null) {
                    relayoutLayoutTop.setVisibility(View.GONE);
                    relayoutLayoutBottom.setVisibility(View.GONE);
                } else {
                    relayoutLayoutTop.setVisibility(View.VISIBLE);
                    if (view.getTag() instanceof Model){
                        Model model = (Model) view.getTag();
                        if (model.isHeader()) {//如果是头部
                            if (view.getTop() > -relayoutLayoutTop.getMeasuredHeight()) {//如果小于头部的高度,表示下面要跟着滑动了,在上滑动的过程中,view.getTop()一直在变小,当view.getTop()
 @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Model model = modelList.get(position);
        model.setPosition(position);
        if (position == 0){
            holder.relativeLayoutTop.setVisibility(View.GONE);
            model.setPreYearMonthDay(model.getYearMonthDay());
            model.setHeader(false);//不要显示标题,因为第一个会在监听那里显示
        }else {
            String preTitle = modelList.get(position - 1).getYearMonthDay();
            model.setPreYearMonthDay(preTitle);
            if(!TextUtils.equals(preTitle,modelList.get(position).getYearMonthDay())){//2个标题不等
                holder.relativeLayoutTop.setVisibility(View.VISIBLE);
                model.setHeader(true);
            }else {
                model.setHeader(false);
                holder.relativeLayoutTop.setVisibility(View.GONE);
            }
        }

        holder.textViewDay.setText(model.getYearMonthDay());
        holder.content.setText(model.getSomthing());
        holder.itemView.setTag(model);
    }
思想:

topView,bottomView,和recyclerViewl里面的header高度都是一样的&recyclerView处于最底层位置


无标题.png

github地址

你可能感兴趣的:(recyclerView 吸顶式效果)