Jetpack Compose:类似于内置`Icons.Default` 的自定义 VectorAsset 图标对象

nba*_*man 6 android kotlin kotlin-android-extensions android-vectordrawable android-jetpack-compose

看起来从res文件夹中的 Android Vector Resources 加载自定义图标的唯一方法是@Composable使用该vectorResource(R.drawable.myVectorName)方法在函数中执行此操作。

这是伟大的,但是我喜欢取的语法VectorAssetsIcon(asset: VectorAsset)类,它看起来像Icon(Icons.Default.Plus)

看起来该vectorResource()方法使用了一个名为的内部方法loadVectorResource(),它用来读取构成矢量资产文件的实际 XML 文件的方法也是内部方法。

我将如何像MyAppIcons.Default.SomeIcon在 Jetpack Compose 中那样创建一个对象?

编辑

所以,我已经找到了一个解决方案。但是,对内置Icon()函数进行我自己的扩展/重载会很好,但我不确定是否有适当的方法来做到这一点。

yaz*_*yed 22

from Resources in Compose

Use the painterResource API to load either vector drawables or rasterized asset formats like PNGs. You don't need to know the type of the drawable, simply use painterResource in Image composables or paint modifiers.

// Files in res/drawable folders. For example:
// - res/drawable-nodpi/ic_logo.xml
// - res/drawable-xxhdpi/ic_logo.png

// In your Compose code
Icon(
    painter = painterResource(id = R.drawable.ic_logo),
    contentDescription = null // decorative element
)
Run Code Online (Sandbox Code Playgroud)


nba*_*man 7

原来我没有用我的大脑。答案很简单。

要点是,Icon() 一个可组合的函数,这意味着当然可以在那里使用vectorResource()

所以,正确的方法不是什么秘密......它是制作自己的MyAppIcon()组件,调用vectorResource()然后返回一个 normal Icon(),如下所示:

正确方式

@Composable
fun MyAppIcon(
    resourceId: Int,
    modifier: Modifier = Modifier,
    tint: Color = AmbientContentColor.current
) {
    Icon(
        asset = vectorResource(id = resourceId),
        modifier = modifier,
        tint = tint
    )
}
Run Code Online (Sandbox Code Playgroud)

然后您可以在其他地方创建一个对象,如下所示:

object MyAppIcons {
    val SomeIcon = R.drawable.someIcon
    val AnotherIcon = R.drawable.anotherIcon
}
Run Code Online (Sandbox Code Playgroud)

当你把两者放在一起时,你可以像这样使用它:

MyAppIcon(MyAppIcons.SomeIcon)
Run Code Online (Sandbox Code Playgroud)

我希望 Google 尽快添加此覆盖,允许我们传入资源 ID。