1. BottomNavigationView导航
BottomNavigationView
用来创建底部导航条,方便用来做页面切换。当有3-5个目标导航页面时,可以使用它来做导航。
1.1. Usage
创建一个menu
资源,最多包含5个MenuItem。
将BottomNavigationView
添加到ContentView的下边。
设置app:menu
属性,引用第一步中创建的menu资源。
创建监听器,通过setOnNavigationItemSelectedListener(…)
。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- Content -->
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:menu="@menu/bottom_nav_menu"
app:labelVisibilityMode="labeled"
app:itemTextColor="@color/bottom_nav_colors"
app:itemIconTint="@color/bottom_nav_colors"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
BottomNavigationView
还支持显示badge,可以通过menuItemId初始化并显示BadgeDrawable,再次调用时会重复利用已存在的BadgeDrawable
。
BadgeDrawable badge = bottomNavigationView.showBadge(menuItemId);
注意: 不要忘记移除BadgeDrawable当不再需要它时。
bottomNavigationView.removeBadge(menuItemId);
如果你只是需要暂时隐藏badge,可以通过改变BadgeDrawable的visibility来实现。
Please see BadgeDrawable
for details on how to update the badge content being displayed.
1.1.1. Handling States
app:itemIconTint
和 app:itemTextColor
使用一个 ColorStateList 用于实现不同状态下对icon图标和字体颜色的控制。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/bn_active" android:state_pressed="true" />
<item android:color="@color/bn_active" android:state_checked="true" />
<item android:color="@color/bn_inactive" />
</selector>
1.1.2. Material Styles
Using BottomNavigationView
with an updated Material theme (Theme.MaterialComponents
) will provide the correct updated Material styles to your BottomNavigationView
s by default. If you need to use an updated BottomNavigationView
and your application theme does not inherit from an updated Material theme, or if you’d like to use a variant style, you can apply one of the updated Material styles directly to your widget in XML:
Component Attribute | Default Theme Attribute Value |
---|---|
itemTextAppearanceActive |
textAppearanceCaption |
itemTextAppearanceInactive |
textAppearanceCaption |
android:background |
colorSurface |
itemIconTint (checked, enabled) |
colorPrimary |
itemIconTint (enabled) |
colorOnSurface at 54% opacity |
itemIconTint (disabled) |
colorOnSurface at 21% opacity |
itemTextColor (checked, enabled) |
colorPrimary |
itemTextColor (enabled) |
colorOnSurface at 54% opacity |
itemTextColor (disabled) |
colorOnSurface at 21% opacity |