【问题标题】:Theme dependent resources in composecompose 中的主题依赖资源
【发布时间】:2021-09-20 15:03:11
【问题描述】:

有没有办法在 Jetpack Compose 中使用主题相关的字符串和可绘制对象?在基于 xml 的布局中,可以使用属性和主题来完成。

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    您可以创建自己的局部变量,如下所示:

    data class AppResources(
        @DrawableRes val someDrawable: Int,
        @StringRes val someString: Int,
    )
    
    val LocalAppResources = staticCompositionLocalOf<AppResources> {
        error("CompositionLocal LocalAppResources not present")
    }
    

    在您的主题中提供所需的值:

    val LightAppResources = AppResources(
        someDrawable = R.drawable.drawable_light,
        someString = R.string.text_light
    )
    
    val DarkAppResources = AppResources(
        someDrawable = R.drawable.drawable_dark,
        someString = R.string.text_dark
    )
    
    @Composable
    fun AppTheme(
        darkTheme: Boolean = isSystemInDarkTheme(),
        content: @Composable () -> Unit
    ) {
        val colors = if (darkTheme) {
            DarkThemeColors
        } else {
            LightThemeColors
        }
        val appResources = if (darkTheme) {
            DarkAppResources
        } else {
            LightAppResources
        }
        MaterialTheme(
            colors = colors,
            typography = typography,
            shapes = shapes,
        ) {
            CompositionLocalProvider(
                LocalAppResources provides appResources,
                content = content
            )
        }
    }
    

    然后你可以像这样在你的应用中使用它:

    Image(
        painterResource(id = LocalAppResources.current.someDrawable),
        "..."
    )
    Text(
        stringResource(id = LocalAppResources.current.someString)
    )
    

    【讨论】:

      【解决方案2】:

      您需要将它们国际化吗?你可以在你的主题对象中创建引用。

      或者创建一个自定义字符串类,您可以在创建主题时加载该类。即只需传入 stringResource(R.string.xxx,...)

      的结果

      主题更实用,所以应该不难做到。

      【讨论】:

      • 你能举个例子吗?如何在主题对象中创建引用?
      • 实际上你可以只做一个 HashMap (所以在主题上键入)并且字符串对象可以只保存你想要改变的字符串的整数引用,例如class ThemeStrings(val title:Int) 所以在您有趣的 AppTheme 中构建 ThemeStrings 并将其添加到 HashMap。所以 hashmap 可以在一个伴生对象中。
      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 2018-07-23
      • 2019-01-17
      相关资源
      最近更新 更多