jetpack

官方上拉加载Paging 配合SwipeRefreshLayou

2020-01-09  本文已影响0人  X小飞侠

下拉刷新Android原生的解决方案是SwipeRefreshLayout,简单好用。
那么上拉加载有没有官方控件呢?有,就是Paging

可惜看了官方文档,要搞一大堆啊,还不如我给RecycleView加个addOnScrollListener监听。
并且官方文档都是依靠Room,自动写好了相关的DataSource.Factory和DataSource。要是我用的是原生Sqlite呢?下面我们来说一说。

1.引入

    implementation 'android.arch.paging:runtime:2.1.0'

2.自定义DataSource和DataSource.Factory

看看Room自动生成的LimitOffsetDataSource,其实也是利用数据库的Limit & Offset关键词,一个是一页的数量;一个是偏移量,每次上拉增加。

可以看到,LimitOffsetDataSource是继承了PositionalDataSource。DataSource其实有三大子类,为什么选择PositionalDataSource呢?
选择正确的数据源类型

DataSource三大子类.png

如果通过网络获取数据,我们可以选择PageKeyDataSource。根据传入的页数参数来加载。或者是帖子场景,根据上一个帖子的ID来获取下一个帖子的数据——官方例子

    private static final int PAGE_SIZE = 5;
    class TaskBeanDataSource extends PositionalDataSource<TaskBean> {
        private int mOffset = 0;
        private List<TaskBean> getTaskBeanList(){
            mOffset += PAGE_SIZE;
            return DBManager.getInstance().getTaskBeanList(PAGE_SIZE, mOffset);
        }

        @Override
        public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<TaskBean> callback) {
            List<TaskBean> taskPackageList = getTaskBeanList();
            int totalCount = taskPackageList.size();
            int position = computeInitialLoadPosition(params, totalCount);
            int loadSize = computeInitialLoadSize(params, position, totalCount);
            callback.onResult(taskPackageList, position, loadSize);
        }

        @Override
        public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<TaskBean> callback) {
            List<TaskBean> taskPackageList = getTaskBeanList();
            callback.onResult(taskPackageList);
        }

    }

    class TaskBeanDataSourceFactory extends DataSource.Factory<Integer, TaskBean> {

        @Override
        public DataSource<Integer, TaskBean> create() {
            return new TaskBeanDataSource();
        }

    }

PS:其实这里用不到三个参数,setEnablePlaceholders设为false,调两个参数的方法就行了,但发现用三个参数的也不影响。

            //callback.onResult(taskPackageList, position, loadSize);
            callback.onResult(taskPackageList, position);
image.png

数据库操作也利用Limit & Offset

    public List<TaskBean> getTaskBeanList(int pageSize, int offset) {
        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        Cursor cursor = null;
        List<TaskBean> taskBeanList = new ArrayList<>();
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT * FROM task LIMIT ").append(pageSize).append(" OFFSET ").append(offset);
            cursor = db.rawQuery(sql.toString(), null);
            while (cursor.moveToNext()) {
                TaskBean taskBean = new TaskBean();
                taskBean.setId(cursor.getString(cursor.getColumnIndex("id")))
                taskBeanList.add(taskBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeCursor(cursor);
        }
        return taskBeanList;
    }

3.修改ViewModel

   public class TaskViewModel extends ViewModel {
    private static final int PAGE_SIZE = 5;
    public final LiveData<PagedList<TaskBean>> mListLiveData;

        public TaskViewModel() {
        TaskBeanDataSourceFactory sourceFactory = new TaskBeanDataSourceFactory();
        PagedList.Config pagedListConfig =
                new PagedList.Config.Builder().setEnablePlaceholders(false)
                        .setInitialLoadSizeHint(PAGE_SIZE)
                        .setPageSize(PAGE_SIZE).build();
        mListLiveData = new LivePagedListBuilder<>(sourceFactory, pagedListConfig).build();
        }
    }
  

注意这里要将setEnablePlaceholders设为false,如果设为true,那么就自动加载不了了。
因为这个这个要起作用,需要知道所有数据的大小,所以还是设为false吧。(话说设为true,出现占位符的效果有人实现过吗,大家可以试试看)
在界面中提供占位符

占位符.png

4.改造原有的adapter,继承PagedListAdapter。

去掉getItemCount()方法,PagedListAdapter会自己处理。
添加DiffUtil对比

 public class TaskListAdapter extends PagedListAdapter<TaskBean, TaskListAdapter.ViewHolder> {

        protected TaskListAdapter() {
            super(DIFF_CALLBACK);
        }

    @Override
    public void onBindViewHolder(@NonNull ConcertViewHolder holder, int position) {
        //通过getItem拿到对应position的bean。这个getItem方法,就会触发PagedList的loadAround(int index)方法,触发加载更多
        TaskBean taskBean = getItem(position);
        //防止第一次加载,数据为空,崩溃
        if (taskBean == null) {
            return;
        }
        holder.tvTitle.setText(taskBean.getTaskName());
    }

    private static DiffUtil.ItemCallback<TaskBean> DIFF_CALLBACK =
            new DiffUtil.ItemCallback<TaskBean>() {
                @Override
                public boolean areItemsTheSame(TaskBean oldTaskBean, TaskBean newTaskBean) {
                    return oldTaskBean == newTaskBean;
                }

                @Override
                public boolean areContentsTheSame(TaskBean oldTaskBean, TaskBean newTaskBean) {
                    return oldTaskBean.getIndex().equals(newTaskBean.getIndex());
                }
            };
    }

5.绑定数据

    public class TaskListActivity extends AppCompatActivity {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            TaskListViewModel viewModel = ViewModelProviders.of(this).get(TaskListViewModel.class);
            TaskListAdapter adapter = new TaskListAdapter();
            viewModel.taskBeanList.observe(this, adapter::submitList);
            recyclerView.setAdapter(adapter);
        }
    }

ps: adapter::submitList这个双引号操作符,是Java8之后新增的,方法引用。
最原始的表达:

        viewModel.taskBeanList.observe(this, new Observer<PagedList<TaskBean>>() {
            @Override
            public void onChanged(PagedList<TaskBean> taskBeans) {
                mTaskListAdapter.submitList(taskBeans);
            }
        });

使用lambda:

        viewModel.taskBeanList.observe(this, taskBeans -> mTaskListAdapter.submitList(taskBeans));

使用双冒号,省略了参数:

        viewModel.taskBeanList.observe(this, mTaskListAdapter::submitList);

6.配合SwipeRefreshLayout使用

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshListener() {
            @Override
            public void onRefresh() {
                viewModel.invalidateDataSource();
            }
        });

         viewModel.taskBeanList.observe(this, new Observer<PagedList<TaskBean>>() {
            @Override
            public void onChanged(PagedList<TaskBean> taskBeans) {
                mTaskListAdapter.submitList(taskBeans);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });

        在viewModel添加invalidateDataSource方法,作用就是让现有的数据源失效。
        public void invalidateDataSource () {
            mListLiveData.getValue().getDataSource().invalidate();
        }

并且修改TaskBeanDataSource ,下拉刷新了,总要把offset置为0吧。

 class TaskBeanDataSource extends PositionalDataSource<TaskBean> {
        private int mOffset = 0;

        private List<TaskBean> getTaskBeanListInit() {
            mOffset = 0;
            return DroneDBManager.getInstance().getTaskBeanList(PAGE_SIZE, mOffset);
        }

        private List<TaskBean> getTaskBeanList() {
            mOffset += PAGE_SIZE;
            return DroneDBManager.getInstance().getTaskBeanList(PAGE_SIZE, mOffset);
        }

        @Override
        public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<TaskBean> callback) {
            List<TaskBean> taskPackageList = getTaskBeanListInit();
            int totalCount = taskPackageList.size();
            int position = computeInitialLoadPosition(params, totalCount);
            int loadSize = computeInitialLoadSize(params, position, totalCount);
            callback.onResult(taskPackageList, position, loadSize);
        }

        @Override
        public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<TaskBean> callback) {
            List<TaskBean> taskPackageList = getTaskBeanList();
            callback.onResult(taskPackageList);
        }

    }

官方的坑

官方实现invalidateDataSource()方法是这样的——考虑内容更新的运作方式
DataSourceFactory:

    public class ConcertTimeDataSourceFactory
            extends DataSource.Factory<Date, Concert> {
        private MutableLiveData<ConcertTimeDataSource> sourceLiveData =
                new MutableLiveData<>();

        private ConcertDataSource latestSource;

        @Override
        public DataSource<Date, Concert> create() {
            latestSource = new ConcertTimeDataSource();
            sourceLiveData.postValue(latestSource);
            return latestSource;
        }
    }
    

viewModel:

    public class ConcertTimeViewModel extends ViewModel {
        private LiveData<PagedList<Concert>> concertList;
        private DataSource<Date, Concert> mostRecentDataSource;

        public ConcertTimeViewModel(Date firstConcertStartTime) {
            ConcertTimeDataSourceFactory dataSourceFactory =
                    new ConcertTimeDataSourceFactory(firstConcertStartTime);
            mostRecentDataSource = dataSourceFactory.create();
            concertList = new LivePagedListBuilder<>(dataSourceFactory, 50)
                    .setFetchExecutor(myExecutor)
                    .build();
        }

        public void invalidateDataSource() {
            mostRecentDataSource.invalidate();
        }
    }
    

我试了过,用 mostRecentDataSource = dataSourceFactory.create();这个来操作,根本不会重新触发DataSource的loadInitial方法。
另外这个sourceLiveData什么鬼,根本没地方用到。这就是官方文档诡秘之处;要不造一个对象没地方用到,要不用到一个对象却不知道哪里生成的

其实要这个sourceLiveData要用也是可以,但是要这样用:

    public class ConcertTimeViewModel extends ViewModel {
        private LiveData<PagedList<Concert>> concertList;
        private DataSource<Date, Concert> mostRecentDataSource;
        private final ConcertTimeDataSourceFactory mSourceFactory;

        public ConcertTimeViewModel(Date firstConcertStartTime) {
            mSourceFactory =
                    new ConcertTimeDataSourceFactory(firstConcertStartTime);
            mostRecentDataSource = dataSourceFactory.create();
            concertList = new LivePagedListBuilder<>(dataSourceFactory, 50)
                    .setFetchExecutor(myExecutor)
                    .build();
        }

        public void invalidateDataSource() {
            //mostRecentDataSource.invalidate();
            mSourceFactory.sourceLiveData.getValue().invalidate();
        }
    }

总结

  1. 你如果不是通过Room使用Paging,那么就要自定义DataSource+DataSource.Factory+(PagedListAdapter用不用room都要),相比用RecycleView的addOnScrollListener监听来实现上拉加载,省略了是否到底的判断。
  2. 造成列表数据是一次性获取全部数据的假象,一直往上拉一直出数据。貌似是一次全部获取的,其实是分段加载的。

你是怎么看待官方上拉加载Paging?你会考虑用?,大家评论评论呗。

上一篇下一篇

猜你喜欢

热点阅读