title: Android分頁組件Paging簡單使用
date: 2018-10-10 17:03:23
tags: Paging
2018-12.21更新
發(fā)現(xiàn)loadRange()方法似乎是在線程中執(zhí)行的,所以這個方法內(nèi)通過同步網(wǎng)絡(luò)請求獲取數(shù)據(jù),重新修改了代碼,提供了一些之前忽略的代碼。
1.簡介:
Paging組件是Google新推出的分頁組件,可以輕松幫助開發(fā)者實現(xiàn)RecyclerView中分頁加載功能。
本文先開坑,等以后用到在詳細寫明。
推薦博客:http://www.itdecent.cn/p/1bfec9b9612c
2.Paging庫引入:
在gradle中引入:
implementation 'android.arch.paging:runtime:1.0.0'
剛引入就遇到了錯誤,真是一個不友好的開始:
Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
目測,是導(dǎo)入重復(fù)的包,這個出錯的地方還是google自己的東西。
“大水沖了龍王廟,自家人打自家人”?
出現(xiàn)沖突的是下面這個包:
compile 'com.android.support:design:26.1.0'
google了一下,在stackoverflow中找到了解決辦法:
https://stackoverflow.com/questions/49028119/multiple-dex-files-define-landroid-support-design-widget-coordinatorlayoutlayou
即用編譯版本改成27,并且把對應(yīng)的庫版本也改為27
implementation 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:design:27.1.1'
問題了解決了,接下來我們看看他的工作原理
3.工作原理

這是官方提供的原理圖,很清楚地看到從DataSource到PagedList, PagedListAdapter最后是我們的recyclerview,我們先眼熟這幾個名字,下文會常常出現(xiàn)。
這里采用的是MVVM架構(gòu)。
3.1 Adapter構(gòu)建
public class AdapterPaging extends PagedListAdapter<VideoInfo, AdapterPaging.ViewHolder> {
private Context mContext;
public static final DiffUtil.ItemCallback<VideoInfo> mDiffCallback = new AdapterPaging.VideoInfoItemCallback();
protected AdapterPaging() {
super(mDiffCallback);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
VideoInfo videoInfo = getItem(position);
}
static class ViewHolder extends RecyclerView.ViewHolder{
private LinearLayout ll_videoInfo;
public ViewHolder(View itemView) {
super(itemView);
ll_videoInfo = itemView.findViewById(R.id.ll_video_info);
}
}
private static class VideoInfoItemCallback extends DiffUtil.ItemCallback<VideoInfo>{
@Override
public boolean areItemsTheSame(VideoInfo oldItem, VideoInfo newItem) {
return oldItem.getUrl() == newItem.getUrl();
}
@Override
public boolean areContentsTheSame(VideoInfo oldItem, VideoInfo newItem) {
return (oldItem == newItem);
}
}
}
大致的4個不同如下:
- Adapter不再繼承自RecyclerView.Adapter,改為繼承自PagedListAdapter,因為PagedListAdapter就是RecyclerView.Adapter的一個子類。
- 定義內(nèi)部回調(diào)接口VideoInfoItemCallback繼承自DiffUtil.ItemCallback<VideoInfo>,并且實例化一個父類引用指向子類(VideoInfoItemCallback)對象
public static final DiffUtil.ItemCallback<VideoInfo> mDiffCallback = new AdapterPaging.VideoInfoItemCallback(); - 重寫構(gòu)造方法,無需參數(shù)傳入,調(diào)用父類構(gòu)造方法將mDiffCallback傳入。
- 通onBindViewHolder中過調(diào)用getItem(position);獲得指定位置的數(shù)據(jù)對象。
因為Adapter中不再需要維護一個數(shù)據(jù)List了,PagedListAdapter中已經(jīng)維護有,并且提供getItem()方法訪問。
3.2 在Activity中的使用
在使用Paging后,我們無需向Adapter中在傳入數(shù)據(jù)源List,我們需要構(gòu)造LiveData。
LiveData需要DataSource.Factory對象和PagedList.Config對象,只是實例化DataSource.Factory對象需要額外兩個步驟
DataSource.Factory是一個抽象類,實例化時需要實現(xiàn)create()函數(shù),這個函數(shù)返回值是一個DataSource類對象
DataSource是一個抽象類,他有三個實現(xiàn)子類:(詳細參考原博客:http://www.itdecent.cn/p/95d44c5338fd)
(1)PageKeyedDataSource 按頁加載,如請求數(shù)據(jù)時傳入page頁碼。
(2)ItemKeyedDataSource 按條目加載,即請求數(shù)據(jù)需要傳入其它item的信息,如加載第n+1項的數(shù)據(jù)需傳入第n項的id。
(3)PositionalDataSource 按位置加載,如加載指定從第n條到n+20條。
所以我們捋一下思路,
1)首先要定義一個MyDataSource繼承自DataSource的三個子類之一,
2)再定義一個MyDataSourceFactory繼承自DataSource.Factory,返回值是MyDataSource
3)然后實例化PagedList.Config,這個類提供有Builder(),比較簡單。
4)最后將MyDataSourceFactory對象和PagedList.Config對象傳入new LivePagedListBuilder()中得到liveData數(shù)據(jù)源。
將liveData數(shù)據(jù)源和Adapter綁定是通過觀察者模式實現(xiàn),調(diào)用liveData.observe()。
//定義MyDataSource類,繼承自DataSource三個子類之一
private class MyDataSource extends PositionalDataSource<Movie.SubjectsBean>{
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<Movie.SubjectsBean> callback) {
callback.onResult(initData(), 0, 10);//initData()是我封裝的加載數(shù)據(jù)方法
}
@Override
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<Movie.SubjectsBean> callback) {
callback.onResult(syncRequestData().getSubjects());
}
}
//定義MyDataSourceFactory,是DataSource.Factory的實現(xiàn)類
private class MyDataSourceFactory extends DataSource.Factory<Integer, Movie.SubjectsBean>{
@Override
public DataSource<Integer, Movie.SubjectsBean> create() {
return new MyDataSource();
}
}
//將生產(chǎn)config和liveData的代碼封裝在這個方法中
private void initPaging(){
PagedList.Config config = new PagedList.Config.Builder()
.setPageSize(10) //每頁顯示的詞條數(shù)
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(10) //首次加載的數(shù)據(jù)量
.setPrefetchDistance(5) //距離底部還有多少條數(shù)據(jù)時開始預(yù)加載
.build();
/**
* LiveData用LivePagedListBuilder生成
* LivePagedListBuilder 構(gòu)造方法需要 DataSource.Factory和PagedList.Config
*/
LiveData<PagedList<Movie.SubjectsBean>> liveData = new LivePagedListBuilder(new MyDataSourceFactory(), config)
.build();
//觀察者模式,將Adapter注冊進去,當liveData發(fā)生改變事通知Adapter
liveData.observe(this, new Observer<PagedList<Movie.SubjectsBean>>() {
@Override
public void onChanged(@Nullable PagedList<Movie.SubjectsBean> subjectsBeans) {
adapterHomeInfo.submitList(subjectsBeans);
}
});
}
從上面的代碼我們可以看到,數(shù)據(jù)的入口在MyDataSource的兩個重寫方法里:
initData():就是用于數(shù)據(jù)加載的方法,可以按自己想需求來封裝。
syncRequestData():用于"加載更多"的方法,loadRange()似乎本身就處在子線程中,所以此處可以用同步網(wǎng)絡(luò)請求。
initData()在初始化時調(diào)用,所以要求我們初始化的時候使用的是本地數(shù)據(jù),而來不及進行網(wǎng)絡(luò)請求。
4.加載網(wǎng)絡(luò)數(shù)據(jù)
這么好的控件,我無論如何都想用于純網(wǎng)絡(luò)加載。想這么做也很簡單,因為我們已經(jīng)把與初始化相關(guān)的代碼封裝到initPaging()中了。
我們只需要在合適的時候進行初始化,就能達到延遲加載的目的了。比如,我們可以用handler和網(wǎng)絡(luò)請求實現(xiàn)消息異步處理,在handler的中調(diào)用initPaging(),這樣就可以不需要本地數(shù)據(jù)進行初始化了。
public static final String MOVIE_REQUEST= 1;
private Movie movie;
private MyHandler handler = new MyHandler(this);
//定義一個MyHandler,用弱引用防止內(nèi)存泄漏
private static class MyHandler<T> extends Handler {
WeakReference<ActivityHome> weakReference;
public MyHandler(ActivityHome activityHome){
weakReference = new WeakReference<ActivityHome>(activityHome);
}
@Override
public void handleMessage(Message msg) {
ActivityHome activity = weakReference.get();
//網(wǎng)絡(luò)狀況不好時,返回obj為null
if(null == msg.obj){
Toast.makeText(activity, "獲取數(shù)據(jù)失敗,請檢查網(wǎng)絡(luò)", Toast.LENGTH_SHORT).show();
return;
}
switch (msg.what){
case MOVIE_REQUEST:
activity.movie = NetWorkUtil.parseJsonWithGson(msg.obj.toString(), Movie.class);
activity.initPaging();
break;
default:
break;
}
}
}
/**
* 初始化數(shù)據(jù)
* @return
*/
private List<Movie.SubjectsBean> initData(){
List<Movie.SubjectsBean> subjectsBeanList = new ArrayList<>();
subjectsBeanList = movie.getSubjects();
return subjectsBeanList;
}
/**
* 進行網(wǎng)絡(luò)請求,同步
* @return
*/
private Movie syncRequestData(){
//將uri中pageindex對應(yīng)的參數(shù)+1,然后進行同步網(wǎng)絡(luò)請求
int currentPageNumber = Integer.parseInt(uri.getQueryParameter("pageindex"));
String url = replace(uri.toString(), "pageindex", currentPageNumber+1+"");
return NetWorkUtil.syncRequest(url, Movie.class);
}
/**
* 進行網(wǎng)絡(luò)請求,異步
* @return
*/
private void asynRequestData(MyHandler handler){
//將uri中pageindex對應(yīng)的參數(shù)+1,然后進行異步網(wǎng)絡(luò)請求
int currentPageNumber = Integer.parseInt(uri.getQueryParameter("pageindex"));
String url = replace(uri.toString(), "pageindex", currentPageNumber+1+"");
NetWorkUtil.sendRequestWithOkHttp(url, MOVIE_REQUEST, handler);
}
//將Uri中的參數(shù)重新賦值
public static String replace(String url, String key, String value) {
if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(key)) {
url = url.replaceAll("(" + key + "=[^&]*)", key + "=" + value);
}
return url;
}
代碼完成了,思路很簡單。
我們只需要在onCreate()中調(diào)用asynRequestData()方法,開始請求數(shù)據(jù),數(shù)據(jù)得到后開始初始化Paging組件,之后通過同步網(wǎng)絡(luò)請求獲得后續(xù)的數(shù)據(jù)。
關(guān)于同步網(wǎng)絡(luò)請求syncRequest()和異步網(wǎng)絡(luò)請求sendRequestWithOkHttp()我就不在這里給出了,大家可以用不同的庫去實現(xiàn)。
5.結(jié)束
又到招聘的季節(jié)了,給大家發(fā)個字節(jié)跳動的內(nèi)推福利:
內(nèi)推碼:UDXTM7B
投遞鏈接:https://job.toutiao.com/campus/
歡迎大家投遞。