问题描述
我想在工具栏操作上显示徽章。徽章编号由 LiveData
值更新。
我是这样贴徽章的:
BadgeUtils.attachBadgeDrawable(inBoxBadgeDrawable,toolbar,R.id.menu_inBox);
我为那次通话尝试了不同的地方,包括 Activity.onCreateOptionsMenu()
、Activity.onPrepareOptionsMenu()
和 androidx.lifgecycle.Observer.onChanged()
。
当有任何变化(工具栏或徽章内容)时,徽章会放错位置,向左移动。或者它被复制到另一个动作。
我猜 attachBadgeDrawable
试图在工具栏中找到 R.id.menu_inBox
的容器视图,插入徽章并更新它的偏移量。如果菜单项的容器视图发生变化,旧的容器视图仍然具有旧徽章,并且没有(明智的)方法可以将其删除。此外,偏移量的应用似乎是堆叠的。
那么,是否还有其他使用工具栏操作图标上的 BadgeDrawable
的方法?
我了解此功能仍处于试验阶段。这个问题会得到解决吗?如果是,大约需要多长时间? (我现在使用 com.google.android.material:material:1.3.0-beta01
。)
这个问题主要针对组件的开发者,因为使用问题应该根据https://github.com/material-components/material-components-android在这里提出。
编辑:我还在项目的跟踪器上创建了一个问题(功能请求):https://github.com/material-components/material-components-android/issues/1967
解决方法
我不确定这是官方解决方案,但这仍然是一种解决方法。我最终在每个 BadgeDrawable
上分离了 onPrepareOptionsMenu
,以防菜单项被更改或重新排列
// This is an indicator of whether we need to show the badge or not
private var isFilterOn: Boolean = false
private var filterBadge: BadgeDrawable? = null
@SuppressLint("UnsafeExperimentalUsageError")
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
val filterItem = menu.findItem(R.id.action_filter)
val toolbar = requireActivity().findViewById<Toolbar>(R.id.toolbar)
if(filterBadge != null) {
BadgeUtils.detachBadgeDrawable(filterBadge!!,toolbar,R.id.action_filter)
filterBadge = null
}
if(isFilterOn) {
filterBadge = BadgeDrawable.create(requireContext()).also {
BadgeUtils.attachBadgeDrawable(it,R.id.action_filter)
}
}
}