转载请注明链接: https://blog.youkuaiyun.com/feather_wch/article/details/88744255
Android paging library是一种分页库。
- 按需加载数据进行展示,避免网络流量和系统资源的损耗
Paging分页库的基本使用
版本号:2019-03-24(1:30)
文章目录
简介
1、分页加载的前世今生
- 分页加载共有两种模式
- 一种是传统的上拉加载更多的分页效果
- 一种是无限滚动的分页效果
2、无限滚动的这种无感知的分页效果无疑是最好的
Paging library就是这种分页库
1、Paging library 的核心组件是PagedList
- 能分页加载app需要的数据(先加载一部分)
- 如果有任何加载的数据变化,一个新的
Pagedlist对象
会更新到LiveData或者RxJava2依赖的对象
中
依赖添加
1、Paging的依赖添加(build.gradle)
/*==========================================
* Paging的依赖
*=============================================*/
implementation "android.arch.paging:runtime:1.0.1"
implementation "android.arch.paging:rxjava2:1.0.1" // Paging对RxJava2的原生支持
数据库中加载数据
1、Activity中使用RecyclerView并且设置对数据的监听
public class DailyPlanActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. RecyclerView + Adapter,正常借助DataBinding进行数据绑定
final GoalListAdapter goalListAdapter = new GoalListAdapter(this);
RecyclerView recyclerView = findViewById(R.id.goal_recyclerview);
// 【LayoutManager!!!!!】
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
// adapter
recyclerView.setAdapter(goalListAdapter);
// 2. ViewModel存放LiveData<PagedList>, 数据改变后调用PagedListAdapter的submitList
GoalViewModel goalViewModel = ViewModelProviders.of(this, new GoalViewModel.GoalViewModelFactory(this))
.get(GoalViewModel.class);
goalViewModel.getGoalList().observe(this, new Observer<PagedList<Goal>>() {
@Override
public void onChanged(@Nullable PagedList<Goal> goals) {
// submitList户必须不过数据刷新和比对
goalListAdapter.submitList(goals);
}
});
}
}
Activity的布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DailyPlanActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/goal_recyclerview"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
2、RecyclerView的Adapter,需要继承自PagedListAdapter, 需要做四部分的工作
- onCreateViewHolder()-创建ViewHolder
public static class GoalViewHolder extends RecyclerView.ViewHolder
- onBindViewHolder()-绑定数据和UI
private static DiffUtil.ItemCallback<Goal> DIFF_CALLBACK
对新旧数据进行差异对比
public class GoalListAdapter extends PagedListAdapter<Goal, GoalListAdapter.GoalViewHolder>{
Context mContext;
public GoalListAdapter(Context context) {
super(DIFF_CALLBACK);
mContext = context;
}
@NonNull
@Override
public GoalViewHolder onCreateViewHolder(@NonNull ViewGroup parent