RecyclerView上拉刷新下拉加载

因为请求的数据是可以分页的,所以下拉加载时直接改变其中的一个数值,可能不是很规范。

mvp请求成功后,在MainActivity里写如下代码

在onCreate()里面

initView();
initData();
在initData()里面

presenter = new UserPresenter(this);
presenter.initUser(1);
---也可以是两个this,这个看presenter类里面的传递来的,不是随便改变的。

//寻找控件
main_srl = (SwipeRefreshLayout) findViewById(R.id.main_srl);
main_rv = (RecyclerView) findViewById(R.id.main_rv);
manager = new LinearLayoutManager(MainActivity.this);
main_rv.setLayoutManager(manager);
main_rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if(newState == RecyclerView.SCROLL_STATE_IDLE){
            int lastVisiblePosition = manager.findLastVisibleItemPosition();
            if(lastVisiblePosition >= manager.getItemCount()-1){
                page=page+1;
                presenter.initUser(page);
                System.out.println("page = " + page);
                Toast.makeText(MainActivity.this, "下拉加载", Toast.LENGTH_SHORT).show();
            }
        }
    }
});

在请求成功数据的方法里面写

//请求数据成功
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        System.out.println("data.toString() = " + data.toString());
//最上面要声明下面这行代码
//private List<Bean.DataBean> data1 = new ArrayList<>();

  //全部添加进去 data1.addAll( data); if( adapter == null){ adapter = new MyAdapter(MainActivity. this, data1); main_rv.setAdapter( adapter); } else{ adapter.notifyDataSetChanged(); //刷新 } adapter.setToastMsg( new MyAdapter.ToastMsg() { @Override public void toastMsg(View view, int pos) { adapter.notifyDataSetChanged(); Toast. makeText(MainActivity. this, data1.get(pos).getOccupation(), Toast. LENGTH_SHORT).show(); } }); main_srl.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { data.clear(); presenter.initUser( 1); Toast. makeText(MainActivity. this, "下拉刷新", Toast. LENGTH_SHORT).show(); main_srl.setRefreshing( false); } }); }});

RecyclerView的适配器里面要自己添加一个接口,并暴露出来

private ToastMsg toastMsg;

public void setToastMsg(ToastMsg toastMsg) {
    this.toastMsg = toastMsg;
}

public interface ToastMsg{
    void toastMsg(View view,int pos);
}

之后在onBindViewHolder里面写

holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        toastMsg.toastMsg(view,position);
        return false;
    }
});

之后就大功告成了,因为数据本身就是分页的,所有很容易就实现






猜你喜欢

转载自blog.csdn.net/color_0716/article/details/78345231