android - 如何使用可组合物在应用程序中动态切换明暗主题
问题描述
您如何通过在应用程序内按下按钮在主题的调色板之间动态切换
这是我到目前为止所做的,但只有当我将 Android 主题切换到深色或浅色模式时才有效
应用主题.Kt
@Model
object ThemeState {
var isLight: Boolean = true
}
@Composable
fun MyAppTheme(
children: @Composable() () -> Unit
) {
MaterialTheme(colors = if (ThemeState.isLight) themeColorsLight else themColorDark) {
children()
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyAppTheme(children = {
Surface {
Greetings(name = "Android")
}
})
}
}
}
@Composable
fun Greetings(name: String) {
Column(modifier = Modifier.fillMaxHeight()) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Hello $name", modifier = Modifier.padding(24.dp),
style = MaterialTheme.typography.h1
)
}
Button(onClick = { ThemeState.isLight = !ThemeState.isLight }) {
Text(text = "Change Theme IsLight:${ThemeState.isLight}")
}
}
}
解决方案
目前我不知道为什么你的代码不起作用,当我发现时我会更新这个答案。
但不要使用if
else
forcolors
参数,而是像这样将它用于整个 MaterialTheme,它会起作用:
@Composable
fun MyAppTheme(
children: @Composable() () -> Unit
) {
if (ThemeState.isLight) {
MaterialTheme(colors = themeColorsLight) {
children()
}
} else {
MaterialTheme(colors = themColorDark) {
children()
}
}
}
更新: 似乎它是 Jetpack Compose dev11 中的错误,我在 dev12 中尝试过,它在那里工作。
注意 1:
@Model
在开发 12 中已弃用,请将您的更改ThemeState
为
object ThemeState {
var isLight by mutableStateOf(true)
}
更多信息:https ://android-review.googlesource.com/c/platform/frameworks/support/+/1311293
注意 2
AndroidStudio 的最新版本中自动导入存在一些问题如果 Idea 抛出错误:Type 'MutableState<TypeVariable(T)>' has no method 'getValue(ThemeState, KProperty<*>)' and thus it cannot serve as a delegate
导入getValue
和SetValue
手动。
import androidx.compose.getValue
import androidx.compose.setValue
从 0.1.0-dev16 开始使用这些导入:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
推荐阅读
- python - 测试描述符是否已经解包的有效方法是什么?
- python-2.7 - 不理解 Python 中 UTF 编码的错误
- informatica - Informatica ETL:如何从导出的 xml 文件中确定目标数据库名称
- operating-system - 调度程序是否确定哪些进程在被阻塞后可以重新进入 CPU?
- css - 有哪些多种方法可以将 div 和图像彼此相邻显示并保持相同的高度响应?
- c++ - 在 ROS 上下文中使用基于 CUDA 的函数的正确方法
- tensorflow - 在 Keras 中添加自定义激活函数
- mongodb - 我们可以在 $project 阶段使用 $gte 运算符在 MongoDB 中使用聚合吗
- css - 角度材料 mat-tab-nav-bar 在左侧制作徽标,标签居中
- c++ - C++ 只使用 h 文件?