撰写中与主题相关的资源

And*_*mer 3 android android-jetpack-compose

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

Phi*_*hov 7

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

data class AppResources(
    @DrawableRes val someDrawable: Int,
    @StringRes val someString: Int,
)

val LocalAppResources = staticCompositionLocalOf<AppResources> {
    error("CompositionLocal LocalAppResources not present")
}
Run Code Online (Sandbox Code Playgroud)

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

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
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的应用程序中使用它,如下所示:

Image(
    painterResource(id = LocalAppResources.current.someDrawable),
    "..."
)
Text(
    stringResource(id = LocalAppResources.current.someString)
)
Run Code Online (Sandbox Code Playgroud)