PullToRefreshRecyclerView——带上拉刷新下拉加载功能的RecyclerView

现在ListView和GridView逐渐被RecyclerView替代,之前基于ListView和GridView的刷新加载框架也已经过时,这里介绍基于RecyclerView的刷新加载框架——PullToRefreshRecyclerView,先看效果。

PullToRefreshRecyclerView——带上拉刷新下拉加载功能的RecyclerView_第1张图片

1. 在Module下的build.gradle中添加依赖

compile 'com.androidkun:pulltorefreshrecyclerview:1.1.0'

2. 在布局文件中添加PullToRefreshRecyclerView控件

 <com.androidkun.PullToRefreshRecyclerView
        android:id="@+id/pullToRefreshRV"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

3. 初始化PullToRefreshRecyclerView并设置属性和回调

 pullToRefreshRV = (PullToRefreshRecyclerView) findViewById(R.id.pullToRefreshRV);
 LinearLayoutManager layoutManager = new LinearLayoutManager(this);
 layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
 pullToRefreshRV.setLayoutManager(layoutManager);
 adapter = new ModeAdapter(this, R.layout.item_mode,data);
 pullToRefreshRV.setAdapter(adapter);
 //是否开启下拉刷新功能
pullToRefreshRV.setPullRefreshEnabled(true);
//是否开启上拉加载功能
pullToRefreshRV.setLoadingMoreEnabled(true);
 //设置是否显示上次刷新的时间
 pullToRefreshRV.displayLastRefreshTime(true);
 //设置刷新回调
 pullToRefreshRV.setPullToRefreshListener(this);
 //主动触发下拉刷新操作
 //pullToRefreshRV.onRefresh();

如果想使用网格列表,则相应设置布局管理者为网格布局管理者就行了

 GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
 recyclerView.setLayoutManager(gridLayoutManager);

此外也可以通过 setRefreshingResource(int resId)setLoadMoreResource(int resId)自定义刷新箭头和加载的图标。

4.处理刷新加载逻辑

 @Override
    public void onRefresh() {
        pullToRefreshRV.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshRV.setRefreshComplete();
                //模拟没有数据的情况
                data.clear();
                adapter.notifyDataSetChanged();
            }
        }, 3000);
    }

    @Override
    public void onLoadMore() {
        pullToRefreshRV.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshRV.setLoadMoreComplete();
                //模拟加载数据的情况
                int size = data.size();
                for (int i = size; i < size + 4; i++) {
                    data.add("" + i + i + i + i);
                }
                adapter.notifyDataSetChanged();
            }
        }, 3000);
    }

框架中提供封装好的BaseAdapter,减少编写相同的代码,提高开发效率,Demo中的ModeAdapter就是继承了BaseAdapter,代码如下:

public class ModeAdapter extends BaseAdapter {

    public ModeAdapter(Context context, int layoutId, List datas) {
        super(context, layoutId, datas);
    }

    @Override
    public void convert(ViewHolder holder, Object o) {
        holder.setText(R.id.textView, (String) o);
    }

}

如果引入PullToRefreshRecyclerView后APP名称被替换,则处理一下国际化即可,新建values-zh文件夹和strings.xml文件,添加app_name属性,如下图:

PullToRefreshRecyclerView——带上拉刷新下拉加载功能的RecyclerView_第2张图片

——————————————————————————————————————————

如果对你有帮助,请点击下方Source到GitHub给个Star,谢谢!

Source

Demo

你可能感兴趣的:(开源框架)