虽然不完全回答了问题,但也许可以帮助需要的人...
如果您正在使用Jetpack Compose并且想在使用ImageVector
(如Icons.Filled.Favorite
)和使用可绘制资源之间获得灵活性,则可以通过使用辅助类来实现,例如以下内容:
class IconResource private constructor(
@DrawableRes private val resID: Int?,
private val imageVector: ImageVector?
) {
@Composable
fun asPainterResource(): Painter {
resID?.let {
return painterResource(id = resID)
}
return rememberVectorPainter(image = imageVector!!)
}
companion object {
fun fromDrawableResource(@DrawableRes resID: Int): IconResource {
return IconResource(resID, null)
}
fun fromImageVector(imageVector: ImageVector?): IconResource {
return IconResource(null, imageVector)
}
}
}
使用该类,您可以相应地创建您的密封类:
sealed class Screen(val route: String, @StringRes val resourceId: Int, icon: IconResource) {
object Home : Screen(
"home", R.string.something,
IconResource.fromDrawableResource(R.drawable.outline_home_black_24)
)
object History : Screen(
"history", R.string.something,
IconResource.fromImageVector(Icons.Filled.Favorite)
)
}
然后,只需调用您的可组合函数:
navigationItems.forEach { screen ->
BottomNavigationItem(icon = {
Icon(
screen.icon.asPainterResource(),
contentDescription = null
)
}
...
}
更新
我已发布了一个包含该实现的库,如果需要,可以在此处找到:https://github.com/ygorluizfrazao/compose-resources
希望能帮到你。