简体   繁体   English

如何从资源中设置 ImageVector?

[英]How to set an ImageVector from resource?

I'm trying to set an icon for bottom navigation like so:我正在尝试为底部导航设置一个图标,如下所示:

sealed class Screen(val route: String, val label: String, val icon: ImageVector) {
    object Home : Screen("home", "Home",R.drawable.outline_home_black_24)
    object History : Screen("history", "History", R.drawable.outline_history_black_24)
}

But it says I need to switch the parameter to Int.但它说我需要将参数切换为 Int。 Help is appreciated, thanks.感谢您的帮助,谢谢。 :) :)

Yes.是的。 Refrences like R.drawable.outline_home_black_24 is not the actual ImageVector but Int references to help get them in code.R.drawable.outline_home_black_24这样的引用不是实际的ImageVector而是 Int 引用,以帮助在代码中获取它们。 To get the actual image you should use something like ContextCompat.getDrawable(context, R.drawable.***) to get the actual Drawable file.要获取实际图像,您应该使用ContextCompat.getDrawable(context, R.drawable.***)之类的东西来获取实际的Drawable文件。 This means that the correct usage should be这意味着正确的用法应该是

sealed class Screen(val route: String, val label: String, @DrawableRes val icon: Int)

The extra annotation throws a warning if a drawable resource which is something like R.drawable.*** is not passed如果未传递类似于R.drawable.***的可绘制资源,则额外的注释会引发警告

Try this尝试这个

sealed class Screen(val route: String, val label: String, val icon: ImageVector) {
    object Home : Screen("home", "Home", painterResource(id = R.drawable.outline_home_black_24))
    object History : Screen("history", "History", painterResource(id = R.drawable.outline_history_black_24))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM