Home > Back-end >  How to set an ImageVector from resource?
How to set an ImageVector from resource?

Time:12-24

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. :)

CodePudding user response:

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

CodePudding user response:

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