Paging 分页加载

1. build.gradle 添加引用库

    def paging_version = "3.1.1"// //google分页库 无感知预加载implementation "androidx.paging:paging-runtime:$paging_version"// alternatively - without Android dependencies for tests//testImplementation "androidx.paging:paging-common:$paging_version"def lifecycle_version = "2.6.0-alpha01"// ViewModelimplementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"// ViewModel utilities for Compose//implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle_version"// Saved state module for ViewModelimplementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"def room_version = "2.4.3"implementation "androidx.room:room-runtime:$room_version"annotationProcessor "androidx.room:room-compiler:$room_version"implementation "androidx.room:room-paging:$room_version"

2. 数据库管理

  2.1 Student.java

@Entity(tableName = "student_table")
public class Student {@PrimaryKey(autoGenerate = true)private int id;@ColumnInfo(name = "student_number")private int studentNumber;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getStudentNumber() {return studentNumber;}public void setStudentNumber(int studentNumber) {this.studentNumber = studentNumber;}
}

  2.2 StudentDao.java

@Dao
public interface StudentDao {@Insertvoid insertStudents(Student... students);@Query("DELETE FROM student_table")void deleteAllStudents();@Query("SELECT * FROM student_table ORDER BY id")PagingSource getAllStudents();// DataSource.Factory getAllStudents();
}

  2.3 StudentsDatabase.java

@Database(entities = {Student.class}, version = 1, exportSchema = false)
public abstract class StudentsDatabase extends RoomDatabase {public static StudentsDatabase instance;public static synchronized StudentsDatabase getInstance(Context context) {if (instance == null) {instance = Room.databaseBuilder(context, StudentsDatabase.class, "students_database").build();}return instance;}public abstract StudentDao getStudentDao();
}

3. 创建列表视频器

  3.1 布局文件 cell.xml



  3.2 MyPagedAdapter.java

public class MyPagedAdapter extends PagingDataAdapter {public MyPagedAdapter() {super(new DiffUtil.ItemCallback() {@Overridepublic boolean areItemsTheSame(@NonNull Student oldItem, @NonNull Student newItem) {return oldItem.getId() == newItem.getId();}@Overridepublic boolean areContentsTheSame(@NonNull Student oldItem, @NonNull Student newItem) {return oldItem.getStudentNumber() == newItem.getStudentNumber();}});}@NonNull@Overridepublic MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {LayoutInflater inflater = LayoutInflater.from(parent.getContext());View view = inflater.inflate(R.layout.cell, parent, false);return new MyViewHolder(view);}@Overridepublic void onBindViewHolder(@NonNull MyViewHolder holder, int position) {Student student = getItem(position);if (student == null) {holder.textView.setText("loading");} else {holder.textView.setText(String.valueOf(student.getStudentNumber()));}}static class MyViewHolder extends RecyclerView.ViewHolder {TextView textView;public MyViewHolder(@NonNull View itemView) {super(itemView);textView = itemView.findViewById(R.id.textView);}}
}

4. 调用测试页

  4.1 activity_main.xml



  4.2 MainActivity.xml

public class MainActivity extends AppCompatActivity {RecyclerView recyclerView;Button btnPopulate, btnClear;StudentDao studentDao;StudentsDatabase studentsDatabase;MyPagedAdapter pagedAdapter;LiveData> allStudentsLivePaging;//LiveData> allStudentsLivePaged;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);recyclerView = findViewById(R.id.recyclerView);pagedAdapter = new MyPagedAdapter();recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));recyclerView.setAdapter(pagedAdapter);studentsDatabase = StudentsDatabase.getInstance(this);studentDao = studentsDatabase.getStudentDao();//allStudentsLivePaging =   new LivePagedListBuilder<>(studentDao.getAllStudents(),30).build();//初始化配置,可以定义最大加载的数据量Pager pager = new Pager<>(new PagingConfig(20), () -> studentDao.getAllStudents());allStudentsLivePaging = PagingLiveData.getLiveData(pager);allStudentsLivePaging.observe(this, new Observer>() {@Overridepublic void onChanged(PagingData pagingData) {pagedAdapter.submitData(getLifecycle(), pagingData);}});btnPopulate = findViewById(R.id.btn_populate);btnClear = findViewById(R.id.btn_clear);btnPopulate.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Student[] students = new Student[500];for (int i = 0; i < 500; i++) {Student student = new Student();student.setStudentNumber(i);students[i] = student;}new InsertAsyncTack(studentDao).execute(students);}});btnClear.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {new ClearAsyncTack(studentDao).execute();}});}static class InsertAsyncTack extends AsyncTask {StudentDao studentDao;public InsertAsyncTack(StudentDao studentDao) {this.studentDao = studentDao;}@Overrideprotected Void doInBackground(Student... students) {studentDao.insertStudents(students);return null;}}static class ClearAsyncTack extends AsyncTask {StudentDao studentDao;public ClearAsyncTack(StudentDao studentDao) {this.studentDao = studentDao;}@Overrideprotected Void doInBackground(Void... voids) {studentDao.deleteAllStudents();return null;}}
}

5. 效果图

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部