RecycleView 底部监听

防京东订单滑动到底部 时显示一个正在加载的条目先上图


RecycleView 底部监听_第1张图片

首先自定义一个类集成RecycleView 重写 onScrollStateChange  和 OnChildAttachedToWindow方法

@Override
public void onScrollStateChanged(int state) {
    super.onScrollStateChanged(state);
   //当滚动状态为停止时开始回调接口
 if (state == SCROLL_STATE_IDLE && isBottom) {
      onUpLoadListener.upLoad();
    }
}

@Override
public void onChildAttachedToWindow(View child) {
    super.onChildAttachedToWindow(child);
    UpLoadVH childViewHolder = (UpLoadVH) getChildViewHolder(child);

    if (childViewHolder.tag == getAdapter().getItemCount() - 1) {
           //当viewHolder的tag与条目数相等时最后一个条目出现在屏幕底部
         isBottom = true;
    } else {
        isBottom = false;
    }
}
自定义有一个类继承RecycleView的ViewHolder 添加一个tag属性

public class UpLoadVH extends RecyclerView.ViewHolder {

    public int tag;

    public UpLoadVH(View itemView) {
        super(itemView);
    }
}

在adapter 中给ViewHolder的tag赋值 ,

@Override
public void onBindViewHolder(UpLoadVH holder, int position) {
    holder.tag = position;
    if (getItemViewType(position) == 0) {
        ViewHodlerItem viewHodlerItem = (ViewHodlerItem) holder;
        Glide.with(mContext).load(R.drawable.freight).bitmapTransform(new CropCircleTransformation(mContext)).crossFade(1000).into(viewHodlerItem.ivHead);
    }
}
下面是重写的RecycleView类的全部代码

package com.ruitukeji.logistics.yihaoSecond.customview;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Administrator on 2017/2/20 0020.
 */

public class UpLoadRecycleView extends RecyclerView {

    private boolean isBottom;

    private OnUpLoadListener onUpLoadListener;

    public void setOnUpLoadListener(OnUpLoadListener onUpLoadListener) {
        this.onUpLoadListener = onUpLoadListener;
    }

    public UpLoadRecycleView(Context context) {
        super(context);
    }

    public UpLoadRecycleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        if (state == SCROLL_STATE_IDLE && isBottom) {
            onUpLoadListener.upLoad();
        }
    }

    @Override
    public void onChildAttachedToWindow(View child) {
        super.onChildAttachedToWindow(child);
        UpLoadVH childViewHolder = (UpLoadVH) getChildViewHolder(child);

        if (childViewHolder.tag == getAdapter().getItemCount() - 1) {
            isBottom = true;
        } else {
            isBottom = false;
        }
    }

    public interface OnUpLoadListener {
        void upLoad();
    }
}







你可能感兴趣的:(RecycleView 底部监听)