简体   繁体   中英

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. 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. To get the actual image you should use something like ContextCompat.getDrawable(context, R.drawable.***) to get the actual Drawable file. 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

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))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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