底部导航栏有很多种实现方式:使用BottomNavigationBar实现、RadioButton实现等,大家在开发时应该根据业务需要选择合适的方式。
一、BottomNavigationView
在Android 9.0及以下使用 BottomNavigationView应引入com.android.support:design:28.0.0
,在Android 10.0中引入com.google.android.material:material:1.0.0
使用BottomNavigationView分为以下几步:
- 导入图片(选中和未选中,如果有)
- 在menu中引用图片资源(如果有两套图片应引用selector.xml)
- 在BottomNavigationView中使用 app:menu 属性引用menu文件
- 在Activity中实现 OnNavigationItemSelectedListener
(一)点击效果
使用BottomNavigationView时我们可以使用以下几个属性为底部导航栏设置点击效果:
属性 | 说明 |
---|---|
app:itemTextAppearanceActive | 选中时的文字效果 |
app:itemTextAppearanceInactive | 未选中时的文字效果 |
app:labelVisibilityMode | auto:自动;labeld:永远显示文字;selected:选中时显示文字;unlabled:永远不显示文字 |
【注意】前两个属性应该引用style文件的内容,设置选中和未选中情况下的textColor
、textSize
。但是这种设置仅限于改变文字的点击效果,除非使用的图片有两套(选中、未选中),否则这种方式不能实现图片的点击效果。
如果想要实现图片的点击效果,但又没有两套图片,可以使用如下方式实现。
/*
* 同一个状态,前面加上“-”表示该状态为false,不加表示该状态为true
*/
int[][] states = new int[][]{
new int[]{android.R.attr.state_selected},
new int[]{-android.R.attr.state_selected}
};
/*
* 此处应该使用getColor()获取color资源,而不是直接使用R.color.xxx
*/
int[] colors = new int[]{
getColor(R.color.colorNavSelectedText),
getColor(R.color.colorNavNormalText)
};
BottomNavigationView navView = findViewById(R.id.nav_view);
ColorStateList stateList = new ColorStateList(states, colors);
navView.setItemIconTintList(stateList);
(二)设置默认选中项
/*
* 设置默认选中的导航菜单项
* 该方法其实是调取了OnNavigationItemSelected()
*/
navView.setSelectedItemId(R.id.menu_news);
navView.setItemIconTintList(null);
(三)新版BottomNavigationView的使用
新版的BottomNavigationView增加了app:itemIconSize
属性,可以非常方便的改变Icon的大小。以下是使用BottomNavigationView会用到的一些属性:
属性 | 说明 |
---|---|
app:elevation | 阴影面积,BottomNavigationView的阴影大小 |
app:itemBackground | Item的背景颜色,@null,表示去除点击时的水波纹效果;指定color,app:labelVisibilityMode 属性为labeled或unlabeled时会覆盖android:background 属性设置的颜色 |
app:itemHorizontalTranslationEnabled | 选中时的动画效果,当app:labelVisibilityMode 属性不为labeled时,选中的item会变大 |
app:itemIconSize | Item的图片大小 |
app:itemIconTint | Item的图片颜色,指定color,会覆盖menu中的selector效果 |
app:itemTextAppearanceActive | 选中时的文字样式 |
app:itemTextAppearanceInactive | 未选中时的文字样式 |
app:itemTextColor | Item的文字颜色,指定color,会覆盖上述两个属性设置的样式 |
app:labelVisibilityMode | auto:item小于3个时显示文字,大于3个时不显示文字;labeled:永远显示文字,且去除水波纹效果;selected:选中时显示文字;unlabled:只显示图片 |
app:menu | 使用的menu文件 |
二、RadioButton
使用RadioButton实现底部导航栏的步骤分为:
- 导入使用的图片(如果需要实现点击时图片和文字均变色的效果,只需要一套图片)
- 编写布局(RadioButton+RadioGroup)
- 实现***RadioGroup.setOnCheckedChangeListener***()
RadioButton的关键属性设置如下:
属性 | 说明 |
---|---|
android:button | 勾选框的背景,@null,取消RadioButton的圆形框 |
android:drawableTop | 设置文字上方的图片 |
android:drawablePadding | 图片和文字之间的间距 |
android:textColor | 需要在res/color下创建selector文件,用于实现选中和未选中状态下的文字颜色切换 |
三、总结
实现方式 | 设置Icon大小 | 设置Icon与文字的边距 | 实现自定义布局 | 是否有切换动画效果 | 是否可以设置默认选中项 |
---|---|---|---|---|---|
BottomNavigationView | ✘(新版可以) | ✘ | ✘ | ✘ | ✔ |
RadioButton | ✘ | ✔ | ✘ | ✘ | ✘ |
从上述内容可以看出,如果没有其他特殊要求,使用BottomNavigationView是最为快速方便,且效果最好,RadioButton次之,如果要实现某些特殊布局,例如在导航栏显示通知数量等,还是需要自己实现底部导航栏效果。