androidkotlinandroid-jetpack-composeandroid-resources

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


Solution

  • 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