一、前言
本文简要记录下流程,代码需要修改后才可以运行。
另外使用paging进行数据加载可以做到数据变动感知,只要数据库数据变动,页面就会自动刷新,无需额外操作
二、相关依赖
<project>/build.gradle
buildscript {
ext {
compose_version = '1.5.4'
}
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.2.1' apply false
id 'com.android.library' version '8.2.1' apply false
id 'org.jetbrains.kotlin.android' version '1.9.22' apply false
}
app/build.gradle
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
compileSdk 34
defaultConfig {
applicationId "com.design.compose"
minSdk 21
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_18
targetCompatibility JavaVersion.VERSION_18
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_18
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion "1.5.8"
kotlinCompilerVersion "1.9.22"
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
namespace 'com.design.compose'
}
dependencies {
implementation 'androidx.core:core-ktx:1.12.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.material3:material3"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2")
implementation("androidx.activity:activity-compose:1.8.1")
implementation(platform("androidx.compose:compose-bom:2023.03.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation "androidx.paging:paging-compose:3.2.1"
// 该依赖需要target为34,可以使用androidx.paging:paging-compose进行替代
// implementation "androidx.paging:paging-compose-android:3.3.0-alpha02"
implementation "androidx.paging:paging-runtime-ktx:3.2.1"
implementation "androidx.paging:paging-common-ktx:3.2.1"
implementation "androidx.room:room-paging:2.6.1"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.2'
implementation 'androidx.activity:activity-compose:1.8.1'
kapt("androidx.room:room-compiler:2.6.1")
implementation("androidx.room:room-runtime:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")
implementation("androidx.room:room-paging:2.4.2")
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
}
二、具体代码
@Parcelize
@Entity(tableName = "user_table")
data class UserInfo(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id: Long = 0L,
@ColumnInfo(name = "name")
var name: String = "",
): Parcelable
@Dao
interface UserDao {
@Query("SELECT * FROM user_table")
fun getAllPagingSource(): PagingSource<Int, UserInfo>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(list: List<UserInfo>)
@Delete
fun deleteAll(list: List<UserInfo>)
}
@Database(entities = [UserInfo::class,], version = 1, exportSchema = true)
abstract class DatabaseManager : RoomDatabase() {
abstract fun getUserDao(): User
companion object {
private const val DATABASE_NAME = "user.db"
private val instance by lazy {
Room.databaseBuilder(App.getInstance(), DatabaseManager::class.java, DATABASE_NAME).build()
}
private fun getUserDao(): AlertDao {
return instance.getUserDao()
}
fun getUserAllPagingSource(): PagingSource<Int,UserInfo>{
return getAlertAreaDao().getAllPagingSource()
}
}
}
ViewModel文章来源:https://www.toymoban.com/news/detail-816408.html
class UserModel : ViewModel(){
val action = MutableLiveData<Action>()
val singlePageSize = 10 //每页显示为10条
fun loadRoomData(): PagingSource<Int, UserInfo> {
return DatabaseManager.getUserAllPagingSource()
}
fun sendAction(action: Action) {
this.action.value = action
}
sealed class Action {
object BACK : Action()
object ADD : Action()
data class DETAILS(val info: UserInfo) : Action()
}
}
UI文章来源地址https://www.toymoban.com/news/detail-816408.html
...
@Composable
fun Center(modifier: Modifier = Modifier, viewModel: UserModel = viewModel()) {
val pager = remember {
Pager(
PagingConfig(
pageSize = viewModel.singlePageSize,
enablePlaceholders = true,
// maxSize = 200
)
) { viewModel.loadRoomData() }
}
val lazyPagingItems = pager.flow.map {
it.map { info ->
// info.name = "${info.name}-->后缀"
info.copy(name = "${info.name}-->后缀")
// Log.e("YM--->", "--->区域时间:${info.areaCreateTime}")
}
}.collectAsLazyPagingItems()
LazyColumn(modifier = modifier) {
if (lazyPagingItems.itemCount == 0) {
item(key = "defaultItem", contentType = "defaultItem") {
DefaultUserItem()
}
}
items(count = lazyPagingItems.itemCount) { index ->
val item = lazyPagingItems[index]
if (item != null) {
UserItem(
modifier = Modifier.clickable(// 去除点击效果
indication = null,
interactionSource = remember {
MutableInteractionSource()
}) {
viewModel.sendAction(UserModel.Action.DETAILS(item))
},
info = item
)
}
}
if (lazyPagingItems.loadState.append == LoadState.Loading) {
item(key = "loadItem", contentType = "loadItem") {
CircularProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
}
}
}
...
三、参考链接
- androidx.paging.compose
- Paging 库概览
到了这里,关于Compose中使用paging3进行列表分页加载Room中的数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!