1. 程式人生 > >RecyclerView上拉重新整理下拉載入

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;
    }
});

之後就大功告成了,因為資料本身就是分頁的,所有很容易就實現