data class Score(
val name: String,
var play: Int,
var out: Int,
var total: Int,
var prev: Int
)
var players = remember {mutableListOf<Score>(
Score("Player A", 0, 0, 0, 0),
Score("Player B", 0, 0, 0, 0),
Score("Player C", 0, 0, 0, 0)
)
}
此代码片段定义并初始化 Jetpack Compose 中的数据类。
如何使用自定义保护程序扩展代码并使用 remeberSaved 和 ListSaver 进行恢复,以便在配置更改后状态仍然存在?
我尝试了各种建议但没有成功。
构建解决方案的更有效方法是在文件 MainViewModel.kt 中使用 ViewModel
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.ViewModel
data class Score(
var name: String,
var play: Int,
var out: Int,
var total: Int
)
class MainViewModel : ViewModel() {
val players: SnapshotStateList<Score> = mutableStateListOf(
Score("Player 1", 0, 0, 0),
Score("Player 2", 0, 0, 0),
Score("Player 3", 0, 0, 0)
)
}
在 MainActivity.kt 中,可以使用以下代码访问数据类
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.Composable
@Composable
fun ScoreSummary(
modifier: Modifier = Modifier,
playersViewModel: MainViewModel = viewModel()
) {
val players = playersViewModel.players
}
然后可以使用以下代码读取和更新列表中的数据
for ((index, score) in players.withIndex()) {
Text(text = score.name, fontSize = 24.sp, color = Color.Cyan)
players[index] = players[index].copy(play = players[index].play + 1)
}
必须将其他依赖项添加到项目 build.gradle.kts 中
implementation(libs.androidx.lifecycle.viewmodel.ktx)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.lifecycle.livedata.ktx)
当配置发生更改时,ViewModel 中的数据将被保留