48. Paging的使用

1.确保使用的RecyclerView是androidx.recyclerview.widget.RecyclerView
2.给RecyclerView设置的Adapter不再是RecyclerView.Adapter而是PagedListAdapter
3.在Adapter初始化的时候,传入一个ItemCallback,用于判断item是否是同一个,注意Student要实现equals 和 hashCode两个方法用于比较

     protected MyPageListAdapter() {
        super(new DiffUtil.ItemCallback() {
            @Override
            public boolean areItemsTheSame(@NonNull Student oldItem, @NonNull Student newItem) {
                Log.d("MyPageListAdapter", "areItemsTheSame oldItem.getId() = " + oldItem.getId() + " newItem.getId() = " + newItem.getId());
                return oldItem.getId() == newItem.getId();
            }

            @Override
            public boolean areContentsTheSame(@NonNull Student oldItem, @NonNull Student newItem) {
                Log.d("MyPageListAdapter", "areContentsTheSame oldItem = " + oldItem + " newItem = " + newItem);
                return oldItem.equals(newItem);
            }
        });
    }

4.Adapter需要的数据源由LivePagedListBuilder类提供

        pagedListLiveData = new LivePagedListBuilder(new DataSource.Factory() {
            @NonNull
            @Override
            public DataSource create() {
                return new PositionalDataSource() {
                    @Override
                    public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback callback) {
                        Log.d("StudentViewModel", "loadInitial params = " + params.pageSize + " start position = " + params.requestedStartPosition);
                        callback.onResult(getStudents(0, 20), 0, 1000);
                    }

                    @Override
                    public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback callback) {
                        Log.d("StudentViewModel", "loadRange params = " + params.loadSize + " start position = " + params.startPosition);
                        callback.onResult(getStudents(params.startPosition, params.loadSize));
                    }
                };
            }
        }, 20).build();

5.LivePagedListBuilder build出来的是一种LiveData>类型的数据,通过监听数据的变化来更新adapter

       pagedListLiveData.observe(this, new Observer>() {
            @Override
            public void onChanged(PagedList students) {
                adapter.submitList(students);
            }
        });

你可能感兴趣的:(48. Paging的使用)