将顶部栏添加到底部导航视图项

时间:2019-07-23 09:33:06

标签: android kotlin bottomnavigationview

我希望在选中每个“底部导航视图”项目的顶部时放置一个栏。如下图所示,但我找不到解决方法。enter image description here

我不知道该怎么做

2 个答案:

答案 0 :(得分:0)

如Payam Kokabi所建议,您可以使用selector确定要显示的背景可绘制对象。遵循以下内容应该可以,

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bottom_item_selected" android:state_checked="true"/>
    <item android:drawable="@drawable/bottom_item" android:state_checked="false"/>
</selector>

PS-您可以使用以下方式将选择器设置为项目背景

app:itemBackground="@drawable/bottom_item_selector"

答案 1 :(得分:0)

您可以通过在底部导航上添加一个视图来实现它,检查下面的代码,也可以使用它在底部导航项上添加任何视图,例如徽章,小图标等。< / strong>

栏的布局 xml

<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="2dp"
    android:layout_gravity="center_horizontal"
    android:background="@color/red"
    android:gravity="center"/>

控制器(显示/隐藏)

class BottomNavigationHelper {

    fun showBadge(context: Context, bottomNavigationView: BottomNavigationView, @IdRes itemId: Int) {
        removeBadge(bottomNavigationView, itemId)
        val itemView = bottomNavigationView.findViewById<BottomNavigationItemView>(itemId)
        val badge = LayoutInflater.from(context).inflate(R.layout.layout_red_badge, bottomNavigationView, false)
        itemView.addView(badge)
    }

    fun removeBadge(bottomNavigationView: BottomNavigationView, @IdRes itemId: Int) {
        val itemView = bottomNavigationView.findViewById<BottomNavigationItemView>(itemId)
        if (itemView.childCount == 3) {
            itemView.removeViewAt(2)
        }
    }
}

示例通话

BottomNavigationHelper().showBadge(mContext, bottomNavigationView, R.id.navigation_home)