徽章可绘制不显示 [英] Badge Drawable not showing
问题描述
为什么未在任何地方显示 BadgeDrawable ?我正在尝试添加MaterialCardView
,MaterialButton
等.它没有显示.任何人都有解决此问题的想法?还是拥有与替换该库相同的库?
Why BadgeDrawable is not displayed anywhere? I'm trying to add on MaterialCardView
, MaterialButton
etc. It's not showing. Anyone have ideas how to fix this? Or have the same library that replacing this?
这里的代码:
val badgeDrawable = BadgeDrawable.create(holder.itemView.context)
badgeDrawable.number = 10
badgeDrawable.badgeGravity = BadgeDrawable.TOP_END
badgeDrawable.backgroundColor = holder.itemView.context.getColor(R.color.colorAccent)
holder.itemView.home_cardview.overlay.add(badgeDrawable)
badgeDrawable.updateBadgeCoordinates(holder.itemView.home_cardview, null)
此方法也不起作用:
BadgeUtils.attachBadgeDrawable(badgeDrawable, anchor, null);
在新版本中,compatBadgeParent是必填字段
By the way in new version compatBadgeParent is required field
推荐答案
这是解决方案,由 @ 0X0nosugar 在我的
Here is the solution posted by @0X0nosugar on my question so please go check out his answer and give him a thumbs up. Links placed above, thank you!
BottomNavigationView.getOrCreateBadge()
不仅将BadgeDrawable
分配为前景Drawable,而且还设置了可绘制范围.没有此步骤,它们将停留在(0,0,0,0),因此没有可绘制的对象.
BottomNavigationView.getOrCreateBadge()
does not only assign the BadgeDrawable
as foreground Drawable, but it also sets the drawable bounds. Without this step, they stay at (0,0,0,0), so there is nothing to draw.
为了设置界限,我们为BadgeDrawable
In order to set the bounds, let's introduce an extension function for BadgeDrawable
/**
* Inspired by BadgeUtils in com.google.android.material library
*
* Sets the bounds of a BadgeDrawable
*/
private fun BadgeDrawable.setBoundsFor(@NonNull anchor: View, @NonNull parent: FrameLayout){
val rect = Rect()
parent.getDrawingRect(rect)
this.setBounds(rect)
this.updateBadgeCoordinates(anchor, parent)
}
将此功能与BadgeDrawable一起用于FrameLayout:
Use this function with your BadgeDrawable for FrameLayout:
private fun setFindShiftBadge(state: HomeState) {
val findShiftsBadge = BadgeDrawable.create(this)
// configure the badge drawable
findShiftsBadge.badgeGravity = BadgeDrawable.TOP_END
findShiftsBadge.backgroundColor = resources.getColor(R.color.colorWhite)
findShiftsBadge.badgeTextColor = resources.getColor(R.color.colorPrimary)
findShiftsBadge.number = state.availableShifts.size
// set bounds inside which it will be drawn
findShiftsBadge.setBoundsFor(btn_badge, home_framelayout)
// assign as foreground drawable
home_framelayout.foreground = findShiftsBadge
}
这篇关于徽章可绘制不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!