【发布时间】:2021-09-20 15:03:11
【问题描述】:
有没有办法在 Jetpack Compose 中使用主题相关的字符串和可绘制对象?在基于 xml 的布局中,可以使用属性和主题来完成。
【问题讨论】:
标签: android android-jetpack-compose
有没有办法在 Jetpack Compose 中使用主题相关的字符串和可绘制对象?在基于 xml 的布局中,可以使用属性和主题来完成。
【问题讨论】:
标签: android android-jetpack-compose
您可以创建自己的局部变量,如下所示:
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)
)
【讨论】:
您需要将它们国际化吗?你可以在你的主题对象中创建引用。
或者创建一个自定义字符串类,您可以在创建主题时加载该类。即只需传入 stringResource(R.string.xxx,...)
的结果主题更实用,所以应该不难做到。
【讨论】: