我想从url加载图像到bottomnavigationview的菜单项图标。像instagram一样,我们想在我们的菜单中显示个人资料图像,这可能会在从不同的可用配置文件切换时发生变化。目前,我正在尝试下面的代码,但它不加载图像每次。
val menu = mViewDataBinding?.bnvNavigation?.menu
val menuItem = menu?.findItem(R.id.menu_profile)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
menuItem?.setIconTintList(null)
menuItem?.setIconTintMode(null)
}
Glide.with(this)
.asBitmap()
.load(profilePic)
.apply(
RequestOptions.circleCropTransform()
.placeholder(R.drawable.user_profile_icon_updated)
)
.into(object :
CustomTarget<Bitmap>(UIHelper.dpToPx(this, 24), UIHelper.dpToPx(this, 24)) {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
menuItem?.icon = BitmapDrawable(resources, resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
上面的代码按预期工作,它只是一个传递应用程序上下文到Glide的问题,Glide.with(App.instance)
App是我的应用类
val menu = mViewDataBinding?.bnvNavigation?.menu
val menuItem = menu?.findItem(R.id.menu_profile)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
menuItem?.setIconTintList(null)
menuItem?.setIconTintMode(null)
}
Glide.with(App.instance)
.asBitmap()
.load(profilePic)
.placeholder(getProfilePlaceholderFilled())
.error(getProfilePlaceholderFilled())
.apply(
RequestOptions.circleCropTransform().placeholder(getProfilePlaceholderFilled())
)
.into(object :
CustomTarget<Bitmap>(UIHelper.dpToPx(this, 80), UIHelper.dpToPx(this, 80)) {
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
menuItem?.icon = BitmapDrawable(
resources, resource
)
}
override fun onLoadFailed(errorDrawable: Drawable?) {
menuItem?.icon = errorDrawable
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
我建议你使用芯片导航和创建自定义底部导航,它比默认的android底部导航要好得多,更容易…
如果您有兴趣学习,可以使用本教程https://www.youtube.com/watch?v=DQtdOSN21lQ&feature=emb_logo和库https://github.com/ismaeldivita/chip-navigation-bar
如果你有任何问题,请告诉我,让我回答你