android - 如何在 Jetpack Compose 中将 Color 与 RememberSaveable 结合使用?

标签 android colors android-jetpack-compose

我想在屏幕旋转后保持颜色。但这段代码会抛出一个错误:

var color by rememberSaveable { mutableStateOf(Color.Red) }
java.lang.IllegalArgumentException: MutableState containing Color(1.0, 0.0, 0.0, 1.0, sRGB IEC61966-2.1) cannot be saved using the current SaveableStateRegistry. The default implementation only supports types which can be stored inside the Bundle. Please consider implementing a custom Saver for this class and pass it as a stateSaver parameter to rememberSaveable().

如何为Color实现Saver

最佳答案

以下是创建自定义Saver的方法:

val ColorSaver = run {
    val redKey = "Red"
    val greenKey = "Green"
    val blueKey = "Blue"
    mapSaver(
        save = { mapOf(redKey to it.red, greenKey to it.green, blueKey to it.blue) },
        restore = {
            Color(
                red = it[redKey] as Float,
                green = it[greenKey] as Float,
                blue = it[blueKey] as Float
            )
        }
    )
}

使用示例:

var color by rememberSaveable(stateSaver = ColorSaver) { mutableStateOf(Color.Red) }

阅读官方文档了解更多信息:https://developer.android.com/jetpack/compose/state#mapsaver

关于android - 如何在 Jetpack Compose 中将 Color 与 RememberSaveable 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76907738/

相关文章:

java - 一些字符保存到文本文件中而不是生成的随机数

android - Android 中 SoundPool 的大小限制是多少?

android - Jetpack compose 中的 AppCompatActivity 而不是 ComponentActivity

android - Jetpack 撰写 : ViewTreeLifecycleOwner not found

java - Android 简单方法不起作用?

android - 在 Android 中动态启用/禁用菜单项

java Swing 。如何将颜色强度从黑色更改为白色?

html - 为什么这种 HTML 和 CSS 组合设置字体颜色和样式失败?

java - 如何更改预定义的十六进制颜色的 alpha?

kotlin - Android jetpack compose更改脚手架背景颜色不改变