文章目录
- 一、前言
- 二、相关依赖
- 二、具体代码
- 三、参考链接
一、前言
本文简要记录下流程,代码需要修改后才可以运行
二、相关依赖
<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 falseid 'com.android.library' version '8.2.1' apply falseid '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 34defaultConfig {applicationId "com.design.compose"minSdk 21targetSdk 34versionCode 1versionName "1.0"testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"vectorDrawables {useSupportLibrary true}}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'}}compileOptions {sourceCompatibility JavaVersion.VERSION_18targetCompatibility 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>)@Deletefun deleteAll(list: List<UserInfo>)
}
@Database(entities = [UserInfo::class,], version = 1, exportSchema = true)
abstract class DatabaseManager : RoomDatabase() {abstract fun getUserDao(): Usercompanion 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
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
...
@Composablefun 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}-->后缀"
// Log.e("YM--->", "--->区域时间:${info.areaCreateTime}")}it}.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 库概览