【问题标题】:How to have multiple custom themes in jetpack compose?如何在 jetpack compose 中拥有多个自定义主题?
【发布时间】:2022-10-07 16:47:15
【问题描述】:

我目前的代码如下:


@Composable
fun AppTheme(darkTheme: Boolean = false,
             content: @Composable() () -> Unit) {
    val colors = if (darkTheme) DarkThemeColors else LightThemeColors
    MaterialTheme(
        colors = colors,
        typography = MaterialTheme.typography,
        shapes = MaterialTheme.shapes,
    ) {
        content()
    }
}

我在这样的主要活动中调用:


    @Inject
    lateinit var application: WeatherApplication

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AppTheme(darkTheme = application.isDark.value) {
                WeatherApp(onToggleTheme = { application.toggleLightTheme()} )
            }

切换灯光主题基本上是这样的:
isDark.value = !isDark.value

然后我在像这样的另一个屏幕中调用 onClick:

@Composable
fun SettingsScreen(onToggleTheme: () -> Unit)
IconButton(onClick = onToggleTheme)

这完成了黑暗和光明的主题,现在如果我想要更多的主题怎么办,也许像这样?

@Composable
fun AppTheme(currentTheme: String,
             content: @Composable() () -> Unit) {
    val colors = when (currentTheme) {
        \"Pink\" -> PinkThemeColors
        \"Light\" -> LightThemeColors
        \"Red\" -> RedThemeColors
        \"Rainbow\" -> RainbowTheme
        else -> LightThemeColors
    }
    MaterialTheme(
        colors = colors,
        typography = MaterialTheme.typography,
        shapes = MaterialTheme.shapes,
    ) {
        content()
    }
}

我如何在另一个屏幕的 onClick 按钮中调用它(一个按钮用于红色,另一个用于粉红色等)?

我仍然是初学者,很抱歉有任何困惑,任何帮助将不胜感激。

标签: android kotlin themes android-jetpack-compose android-jetpack


【解决方案1】:

我也是初学者,所以请考虑我只回答您的主要问题,并且我不考虑您的代码是否具有良好的架构或遵循最佳实践(这就是为什么我在示例中也使用硬编码字符串的原因,但你应该避免这种情况。我只是这样做,因为它让你更容易理解解决方案。)。我认为您的主要问题不是您在标题中提出的问题,而是最后一个问题:“我如何在另一个屏幕的 onClick 按钮中调用它(一个按钮用于红色,另一个用于粉红色等)?”。因此,您已经通过使用回调切换布尔变量来实现设置主题,现在您想要的是使用字符串变量从两个以上的主题中进行选择。如果要通过回调传递字符串值,可以执行以下操作:

@Composable
fun SettingsScreen(onChooseTheme: (String) -> Unit) {
    IconButton(onClick = { onChooseTheme("Pink") })
    IconButton(onClick = { onChooseTheme("Light") })
    IconButton(onClick = { onChooseTheme("Red") })
    IconButton(onClick = { onChooseTheme("Rainbow") })
}

未提供 WeatherApplication 类的源代码,但根据您的代码,我认为您希望在层次结构中使用此值,可以这样实现:

SettingsScreen(
    onChooseTheme = { currentTheme = it }
)

it 是你的字符串值的关键字,你也可以像这样重命名它:

SettingsScreen(
    onChooseTheme = { chosenTheme ->
        currentTheme = chosenTheme }
)

希望这会有所帮助,如果您遇到任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多