BottonNavigationView使用
点击tab,tab的文字的颜色切换
- 在res文件下,新建color文件,selector_tab_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/color_4f5356" android:state_checked="false" />
<item android:color="@color/color_0159a5" android:state_checked="true" />
</selector>
- 在布局中添加
app:itemIconTint="@color/selector_tab_color"
app:itemTextColor="@color/selector_tab_color"
labelVisibiltityMode
有四种值:auto selected labeled unlabeled
源码中是这么写的
<attr name="labelVisibilityMode">
<!-- Label behaves as "labeled" when there are 3 items or less, or "selected" when there are
4 items or more. -->
<enum name="auto" value="-1"/>
<!-- Label is shown on the selected navigation item. -->
<enum name="selected" value="0"/>
<!-- Label is shown on all navigation items. -->
<enum name="labeled" value="1"/>
<!-- Label is not shown on any navigation items. -->
<enum name="unlabeled" value="2"/>
</attr>
意思是说 当有三个item时候或者更少的时候,默认labelVisibilityMode是labeled。当是4个item或者更多的时候默认是selected
labeled的模式是这样子的
都显示文字
selected模式是这样子的
只有选中的时候有文字显示
unlabeled模式是这样的
没有文字显示
BottomNavigationView取消水波纹动画
在布局中设置 `app:itemRippleColor="@null"
BottomNavigationView点击事件
//item条目的点击事件
binding.navView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
addAndShowFragment(homeFragment, R.id.nav_host_fragment_activity_main)
}
R.id.navigation_dashboard -> {
addAndShowFragment(dashboardFragment, R.id.nav_host_fragment_activity_main)
}
R.id.navigation_notifications -> {
addAndShowFragment(notificationsFragment, R.id.nav_host_fragment_activity_main)
}
}
true
}
给BottonNavigationView设置角标
代码如下:
val nobage = binding.navView.getOrCreateBadge(R.id.navigation_notifications)
nobage.backgroundColor = resources.getColor(R.color.teal_200)//设置角标的背景颜色
nobage.badgeGravity = BadgeDrawable.TOP_START//设置位置
nobage.number = 99//角标数量
BottomNavigationView 动态显示隐藏MenuItem
之前有这么一个需求,一个APP上架提升之前,我们只显示两个item,当过个三五天后,我们要把隐藏的item显示出来
- remove
val navView: BottomNavigationView = findViewById(R.id.nav_view)
navView.menu.removeItem(R.id.navigation_spacing)
这种方式是直接把这个item删除掉了,是一个不可逆的过程,也就是说删除后没法再显示出来
- setVisible
// 显示
nav_view.menu.findItem(R.id.navigation_test).isVisible = true
// 隐藏
nav_view.menu.findItem(R.id.navigation_test).isVisible = false