Recycleview實(shí)現(xiàn)下拉刷新&上拉加載更多

一.下拉刷新
話不多說,前段時(shí)間做項(xiàng)目的時(shí)候剛用到過,分享出來集思廣益,歡迎指出不足。本文主要利用SwipeRefreshLayout嵌套R(shí)ecycleview實(shí)現(xiàn)簡(jiǎn)單的下拉刷新功能。

1.XML文件:

                       <?xml version="1.0" encoding="utf-8"?>
                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swiperefreshlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:scrollbars="vertical" />

    </android.support.v4.widget.SwipeRefreshLayout>


 </LinearLayout>

2.代碼:Activity的OnCreate方法里只要添加幾行代碼就可實(shí)現(xiàn)下拉刷新的效果

                 swiperefreshlayout.setOnRefreshListener(this);
                 swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
         //發(fā)送網(wǎng)絡(luò)請(qǐng)求
            sendRequest();
         //停止刷新
            swiperefreshlayout.setRefreshing(false);
         //刷新RecycleView
            mRecycleViewAdapter.notifyDataSetChanged();
        }
    });

二.上拉加載更多
看過網(wǎng)上很多關(guān)于上拉加載更多的文章,最后總結(jié)測(cè)試了一下,就有了適合自己的簡(jiǎn)單的上拉加載更多。主要采用Recycleview設(shè)置一個(gè)FootViewHolder,并監(jiān)聽Recycleview的滑動(dòng)狀態(tài)來實(shí)現(xiàn)效果。直接貼代碼吧(Copy不能運(yùn)行,只能自己截取有用的部分加以利用,耐著性子看完,相信會(huì)有收獲哦)

1.XML文件:

                    <?xml version="1.0" encoding="utf-8"?>
                   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swiperefreshlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:scrollbars="vertical" />

    </android.support.v4.widget.SwipeRefreshLayout>

2.代碼(主要為網(wǎng)絡(luò)請(qǐng)求到的數(shù)據(jù)Copy無效,其他各位看官隨意蹂躪):

1.Activity:

            public class MyActivity extends AppCompatActivity {
private NoticeAdapter adapter;
private RecyclerView noticeRecyclerview;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initData();
}

private void initData() {
    //news為你第一次發(fā)送網(wǎng)絡(luò)請(qǐng)求獲取到的List集合,這里就不貼了
    adapter = new NoticeAdapter(this,news);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    noticeRecyclerview.setLayoutManager(linearLayoutManager);
    noticeRecyclerview.setAdapter(adapter);
    noticeRecyclerview.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    noticeRecyclerview.addOnScrollListener(monScrollListener);
    adapter.notifyDataSetChanged();
}
       //本段可直接Copy,作用是監(jiān)聽Recycleview是否滑動(dòng)到底部
private int mLastVisibleItemPosition;
private RecyclerView.OnScrollListener monScrollListener = new RecyclerView.OnScrollListener() {

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            mLastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
        }
        if (adapter != null) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && mLastVisibleItemPosition + 1 == adapter.getItemCount()) {
                //發(fā)送網(wǎng)絡(luò)請(qǐng)求獲取更多數(shù)據(jù)
                sendMoreRequest();
            }
        }
    }


};

private void sendMoreRequest() {
    //可直接查看下面onResponse方法,網(wǎng)絡(luò)請(qǐng)求操作不必細(xì)看
    String url = Constant.BaseUrl + "getNews";
    final String s = MD5Tools.MD5(MD5Tools.MD5("NEW"));
    OkHttpUtils.post().url(url)
            .addParams("FKEY", s)
            .build()
            .execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }
                @Override
                public void onResponse(String response, int id) {
                    NoticeBean noticeBean = new Gson().fromJson(response.toString(), NoticeBean.class);
                    //result == 1表示請(qǐng)求成功
                    if (noticeBean.getResult()== 1){
                        //判斷請(qǐng)求的數(shù)據(jù)集合是否不為空
                        if (noticeBean.getNews().size()!=0){
                            //不為空,則添加數(shù)據(jù)
                            adapter.addList(noticeBean.getNews());
                        }else {
                            //為空,則調(diào)用adapter里面的方法隱藏FootView
                            adapter.setIsLoadMore();
                        }
                    }
                }
            });
}

}

2.Adapter:

 public class NoticeAdapter extends RecyclerView.Adapter{
private List<NoticeBean.NewsBean> list;
private Context mContext;
    //上拉加載更多布局
public static final int view_Foot = 1;
      //主要布局
public static final int view_Normal = 2;
     //是否隱藏
public boolean isLoadMore = false;

public NoticeAdapter(Context mContext, List<NoticeBean.NewsBean> list) {
    this.list = list;
    this.mContext = mContext;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType ==view_Normal ){
        NoticeItemView noticeItemView = new NoticeItemView(mContext);
        NoticeViewHolder viewHolder = new NoticeViewHolder(noticeItemView);
        return viewHolder;
    }else {
        FootView view = new FootView(mContext);
        FootViewHolder footViewHolder = new FootViewHolder(view);
        return footViewHolder;
    }

}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (position == getItemCount()-1){
        FootView itemView = (FootView) holder.itemView;
        if (isLoadMore){
            itemView.setData();
        }else {
            itemView.setVisibility(View.VISIBLE);

        }
    }else {
        NoticeItemView itemView = (NoticeItemView) holder.itemView;
        itemView.setData(list.get(position));
    }

}

@Override
public int getItemCount() {
    return list.size()+1;
}

@Override
public int getItemViewType(int position) {
    if (position == getItemCount()-1){
        return view_Foot;
    }else {
        return view_Normal;
    }
}

public void addList(List<NoticeBean.NewsBean> news) {
    list.addAll(news);
    notifyDataSetChanged();
}

public void setIsLoadMore() {
    this.isLoadMore = true;
    notifyDataSetChanged();
}

static class NoticeViewHolder extends RecyclerView.ViewHolder {
    public NoticeViewHolder(View itemView) {
        super(itemView);
    }
}
static class FootViewHolder extends RecyclerView.ViewHolder {
    public FootViewHolder(View itemView) {
        super(itemView);
    }
}

}

3.FootView為自定義控件,NoticeItemView和FootView大同小異,就不貼代碼了,F(xiàn)ootView代碼如下

       public class FootView extends RelativeLayout {

@BindView(R.id.foot_view_progressbar)
ProgressBar footViewProgressbar;

public FootView(Context context) {
    this(context, null);
}

public FootView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    View.inflate(getContext(), R.layout.foot_view, this);
    ButterKnife.bind(this,this);
}

public void setData() {
footViewProgressbar.setVisibility(GONE);
}

}

4.FootView的XML文件:

        <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
    android:id="@+id/foot_view_progressbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"/>

</LinearLayout>

四.后續(xù)會(huì)更新源碼至GitHub,有興趣的同學(xué)可關(guān)注微信公眾號(hào)MiHomes。

末尾:移動(dòng)互聯(lián)&人力資源交流群,可加微信zy666128入群交流。


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容