美文网首页
Google Paging实例代码讲解

Google Paging实例代码讲解

作者: 虎哥Lovedroid | 来源:发表于2018-08-29 10:11 被阅读0次

1. 实现网络数据分页加载

我们在前面已经知道,Paging库主要由三大组件构成:PagingListPagedListAdapter以及
PagingDataSource。实现了这三大组件,分页加载功能也就实现了。

1.1 三大组件初始化

首先在Fragment或者Activity的onCreate或者onCreateView中初始化PagingList以及Paging,
在这个过程中,将PagingList、PagedListAdapter以及PagingDataSource一并初始化了。
PagingSearchFragment.java


@Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                            Bundle savedInstanceState) {

        new SearchPresenter(mContext,this, Injection.provideSchedulerProvider());

        return super.onCreateView(inflater, container, savedInstanceState);

    }

//initData方法在父类的onCreateView方法中被调用 

@Override

    public void initData() {

        mPagedList = makePageList(null);

        pagingListAdpater = new ContactsPagingListAdpater(mContext);

        resultListView.setAdapter(pagingListAdpater);

        ......

        ......

        pagingListAdpater.submitList(mPagedList);



    }

1.2 PagingList构建

PagingList初始化具体在makePageList中实现,PagingList主要通过PagedList.Config配置参数,通过PagedList.Builder完成构造,具体参数设置以及构造设置参考代码中的注释。


private PagedList mPagedList;

    private PagedList makePageList(String searchStr) {

        mDataSource = new PagingDataSource(mPresenter, searchStr);

        PagedList.Config mPagedListConfig = new PagedList.Config.Builder()

                .setPageSize(20) //分页数据的数量。在后面的DataSource之loadRange中,count即为每次加载的这个设定值。

                //.setPrefetchDistance(10) //def pageSize

                .setEnablePlaceholders(false)//加载数据Item为null时占位

                .setInitialLoadSizeHint(40)

                .build();

        return new PagedList.Builder(mDataSource, mPagedListConfig)

                .setNotifyExecutor(new BackgroundThreadTask()) //初始化阶段启用

                .setFetchExecutor(new MainThreadTask()) //初始化阶段启动

                .setInitialKey(Integer.valueOf(1)) //设置初始化页码

                .build();

    }

1.3 PagingDataSource实现

这里我们根据业务需求,选取PageKeyedDataSource作为数据源,这个数据源主要需要传递Int型的PageNum作为参数实现每一页数据的请求,具体实现请看下面的代码。

public class PagingDataSource extends PageKeyedDataSource<Integer, ContactInfo>{

    private static final String TAG = PagingDataSource.class.getSimpleName();

    private BaseIPVTApiPresenter mBaseIPVTApiPresenter;
    private String mSearchKey;
    int mPageTotal = 1;

    public PagingDataSource(BaseIPVTApiPresenter baseIPVTApiPresenter, String searchKey){
        mBaseIPVTApiPresenter = baseIPVTApiPresenter;
        mSearchKey = searchKey;
    }

    //DataSource执行build()的时候调用
    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, ContactInfo> callback) {
        //加载第一页
        Logger.d(TAG,"[loadInitial]params requestedSize = "+params.requestedLoadSize);//pageSize

        Logger.d(TAG,"[loadInitial]current ThreadName = "+Thread.currentThread().getName());


        if(TextUtils.isEmpty(mSearchKey)){
            return;
        }
        mBaseIPVTApiPresenter.reqOnePageContactList(null, "1", mSearchKey,
                new RequestCallback<HttpOnePage<ContactInfo>>() {
            @Override
            public void processData(HttpOnePage<ContactInfo> data) {
                List<ContactInfo> firstPage = data.list();
                int pageNum = data.pageNum();
                int pageSize = data.pageSize();
                int pageTotal = data.pageTotal();
                mPageTotal = pageTotal;
                Integer prevPageNum = pageNum;
                Integer nextPageNum = pageNum;
                if(pageNum <= 1 ){
                    prevPageNum = null;
                }else{
                    prevPageNum = pageNum -1;
                }

                if(pageTotal <=1){
                    nextPageNum = null;
                } else {
                    nextPageNum = pageNum +1;
                }

                Logger.d(TAG,"[loadInitial]prePageNum = "+prevPageNum+", nextPageNum = "+nextPageNum);

                callback.onResult(firstPage, prevPageNum, nextPageNum);
            }

            @Override
            public void processErrorCode(String errcode) {

            }

            @Override
            public void processException(int errNo) {

            }
        });
    }

    @Override
    public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, ContactInfo> callback) {

        //加载之前
        Logger.d(TAG,"loadBefore");

    }

    @Override
    public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, ContactInfo> callback) {

        if(TextUtils.isEmpty(mSearchKey)){
            return;
        }

        Logger.d(TAG,"[loadAfter]current ThreadName = "+Thread.currentThread().getName());

        Logger.d(TAG,"[loadAfter]params key = "+params.key+",requestedLoadSize = "+params.requestedLoadSize);
        //加载后面的每一页
        mBaseIPVTApiPresenter.reqOnePageContactList(null, String.valueOf(params.key), mSearchKey,
                new RequestCallback<HttpOnePage<ContactInfo>>() {
            @Override
            public void processData(HttpOnePage<ContactInfo> data) {
                Integer nextPage = params.key;
                if(params.key<mPageTotal){
                    nextPage = nextPage+1;
                }else{
                    nextPage = null;
                }
                Logger.d(TAG,"next Page = "+nextPage);
                callback.onResult(data.list(), nextPage);
            }

            @Override
            public void processErrorCode(String errcode) {

            }

            @Override
            public void processException(int errNo) {

            }
        });
    }
}

PagingDataSource 继承自PageKeyedDataSource,实现了loadInitial、loadAfter、loadBefore方法,
其中

  • loadInitial 初始加载数据
  • loadAfter 向后分页加载数据
  • loadBefore 向前分页加载数据
    这三个方法都有两个参数,一个params和一个callback

其中params包装了分页加载的参数,loadInitial中的params为LoadInitialParams包含了requestedLoadSizeplaceholdersEnabled两个属性,requestedLoadSize为加载的数据量,placeholdersEnabled是是否显示占位及当数据为null时显示占位的view

loadBeforeloadAfter中的params为LoadParams包含了key和requestedLoadSize,key即为DataSource<Key, Value>中的key,在这里即为页数

callback 为数据加载完成的回调,loadInitial 中调用调用IPVTApiPresenter加载数据,然后调用callback.onResult告诉调用者数据加载完成。

public abstract void onResult(@NonNull List<Value> data, @Nullable Key previousPageKey,
                @Nullable Key nextPageKey);

onResult 有三个参数,第一个为数据,后面两个即为上一页和下一页

如果我们当前页为第一页即没有上一页,则上一页为null,下一页为2,此时加载的时候会加载当前页和调用loadAfter加载第二页,但不会调用loadBefore因为没有上一页,即previousPageKey为null不会加载上一页

如果我们初始加载的是第三页,则上一页是2,下一页是4,此时加载的时候会加载当前页和调用loadAfter加载第4页,调用loadBefore加载第二页

分页加载的时候会将previousPageKeynextPageKey传递到loadAfterloadBefore中的params.key

loadAfterloadBefore中的params中的key即为我们要加载页的数据,加载完后回调中告知下一次加载数据页数+1或者-1

1.4 PagedListAdapter实现

ContactsPagingListAdpater实现代码如下,这里主要是要实现DiffUtil.ItemCallback接口,然后传给父类PagedListAdapter,用于监听Item数据项变化来更新列表

public class ContactsPagingListAdpater extends PagedListAdapter<ContactInfo, ContactViewHolder>{

    private final Context mContext;
    private int curFragmentType = ProContactsActivity.FRAGMENT_TYPE_CONTACT;
    private boolean isCheckBoxVisible = false;

    private final static DiffUtil.ItemCallback<ContactInfo> mDiffCallback = new DiffUtil.ItemCallback<ContactInfo>() {

        @Override
        public boolean areItemsTheSame(ContactInfo oldItem, ContactInfo newItem) {
            Logger.d("DiffCallback", "areItemsTheSame");
            return oldItem.contactId() == newItem.contactId();
        }

        @Override
        public boolean areContentsTheSame(ContactInfo oldItem, ContactInfo newItem) {
            return oldItem.equals(newItem);
        }
    };

    public ContactsPagingListAdpater(Context context){
        super(mDiffCallback);
        mContext = context;
    }

    @NonNull
    @Override
    public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.contacts_item_layout, parent, false);
        ContactViewHolder holder = new ContactViewHolder(view);
        return holder;
    }

    // 事件回调监听
    private ContactsPagingListAdpater.OnItemClickListener onItemClickListener;

    // 定义点击回调接口
    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    // 定义一个设置点击监听器的方法
    public void setOnItemClickListener(ContactsPagingListAdpater.OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }


    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {

        ContactInfo itemInfo = getItem(position);
        Integer type = itemInfo.type();
        if (type != null && type==1) {
            holder.contactImage.setImageResource(R.drawable.public_equipment_icon);
        } else {
            holder.contactImage.setImageResource(R.drawable.contacts_icon);
        }

        holder.contactName.setText(itemInfo.name());

        if (!isCheckBoxVisible || curFragmentType == ProContactsActivity.FRAGMENT_TYPE_SEARCH) {
            holder.contactCheckBox.setVisibility(View.GONE);
        } else {
            holder.contactCheckBox.setVisibility(View.VISIBLE);
        }
        String state = String.valueOf(itemInfo.state());
        if (state != null) {
            if (state.equals("1")) {
                holder.stateImage.setImageResource(R.drawable.contact_state_online_green);
            } else if (state.equals("2")) {
                holder.stateImage.setImageResource(R.drawable.contact_state_busy_red);
            } else {
                holder.stateImage.setImageResource(R.drawable.contact_state_offline_grey);
            }
        } else {
            holder.stateImage.setImageResource(R.drawable.contact_state_offline_grey);
        }

        /*if (checkedContacts.contains(itemInfo)) {
            holder.contactCheckBox.setChecked(true);
        } else {*/
            holder.contactCheckBox.setChecked(false);
        //}
        //return convertView;

        holder.mItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onItemClickListener.onItemClick(view,position);
            }
        });
    }


}

1.5 网络数据获取

网络数据获取,主要使用一些三方库实现,RxJava用于异步处理,Retrofit+Okhttp用于网络数据
获取,Google AutoValue用于JavaBean处理,moshi Json用于Json解析。

BaseIPVTApiPresenterImpl.java

 @Override
    public void reqOnePageContactList(String departmentId, String pageNum, String searchKey,
                                      RequestCallback<HttpOnePage<ContactInfo>> callback) {
        int expNo = preProcessBeforeRequest();
        if(expNo > NetErrorCode.EXP_NONE){
            callback.processException(expNo);
            return;
        }
        Map<String, String> contactListParams = RequestParamManager.getInstance().
                onePageContactParamsMap(mContext,departmentId,pageNum,searchKey);
        Disposable disposable = Single.defer(()->ServiceGenerator.createService(IPVTService.class)
                .reqContactsPageData(RequestParamManager.getInstance().onePageContactParamsMap(mContext,departmentId,pageNum,searchKey)))
                .compose(relogin())
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(mSchedulerProvider.ui())
                .compose(RxProgress.bindToLifecycle(mActivity, R.string.load_msg))
                .subscribe(listHttpPageResult -> {
                    processResult(listHttpPageResult, callback);
                }, throwable -> {
                   processException(throwable, callback);
                });
        mCompositeDisposable.add(disposable);
    }

Retrofit API 接口如下:

//query contacts page list/ 20 per page
    @GET("pro/contacts/userlist")
    Single<HttpResult<HttpOnePage<ContactInfo>>> reqContactsPageData(@QueryMap Map<String, String> map);

在该Api中,返回的json格式如下:

{
    "data": {
        "list": [{
            "contactId": 19425,
            "departmentId": 0,
            "name": "121",
            "proAccount": "121",
            "state": 1,
            "type": 1
        }
        ......
        ......
        , {
            "contactId": 19423,
            "departmentId": 0,
            "name": "mmey",
            "proAccount": "123",
            "state": 0,
            "type": 1
        }],
        "pageNum": 2,
        "pageSize": 20,
        "pageTotal": 2,
        "searchContent": "1"
    },
    "retCode": "0",
    "timeStamp": "20180829010007"
}

2. 实现本地数据分页加载

相关文章

网友评论

      本文标题:Google Paging实例代码讲解

      本文链接:https://www.haomeiwen.com/subject/bilhwftx.html