BottomNavigationView入门

BottomNavigationView 是 Android 官方提供的底部导航栏组件,旨在简化应用程序中不同功能页面之间的切换。 它通常用于显示三个到五个主要功能项,方便用户快速访问应用的核心部分。
BottomNavigationView一般与fragment配合使用。具体这样配合使用:

  • BottomNavigationView+FragmentContainerView+Fragment
  • BottomNavigationView+ViewPager+Fragment
    如有不对或需要补充的地方欢迎评论区告诉我。

一、简单使用

这里使用BottomNavigationView+FragmentContainerView+Fragment实现布局切换
1. 定义菜单

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/workbenches"
        android:icon="@drawable/baseline_apps_24"
        android:title="@string/workbenches" />
    <item
        android:id="@+id/personal_center"
        android:icon="@drawable/round_person_24"
        android:title="@string/personal_center" />
</menu>

2. 在布局中添加BottomNavigationView

<layout 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">

    <LinearLayout
        android:id="@+id/main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".ui.workbenches.WorkbenchActivity">

        <View
            android:layout_width="match_parent"
            android:layout_height="80dp" />

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fcv"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bnv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_bottom_navigation_bg"
            app:menu="@menu/workbenches" />

    </LinearLayout>
</layout>

3. 设置监听器 切换布局

public class WorkbenchActivity extends BaseActivity<WorkbenchesViewModel, ActivityWorkbenchBinding> {

    private ModuleFragment moduleFragment;
    private UserFragment userFragment;

    @Override
    protected WorkbenchesViewModel createViewModel() {
        return new ViewModelProvider(this).get(WorkbenchesViewModel.class);
    }

    @Override
    protected ActivityWorkbenchBinding createDataBinding() {
        return ActivityWorkbenchBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        moduleFragment = new ModuleFragment();
        userFragment = new UserFragment();
        // 默认显示工作台
        getSupportFragmentManager().beginTransaction().replace(R.id.fcv, moduleFragment).commit();

        binding.bnv.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.workbenches) {
                    getSupportFragmentManager().beginTransaction().replace(R.id.fcv, moduleFragment).commit();
                } else if (itemId == R.id.personal_center) {
                    getSupportFragmentManager().beginTransaction().replace(R.id.fcv, userFragment).commit();
                }
                return true;
            }
        });
    }

    @Override
    protected void initData() {

    }
}

在这里插入图片描述

二、自定义选中状态等

1. 选中状态(自定义图标和文本颜色)
res/color 目录下创建一个名为 selector_bottom_navigation_item.xml 的文件

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

在布局文件中,使用 app:itemIconTintapp:itemTextColor 属性引用上述颜色选择器

<com.google.android.material.bottomnavigation.BottomNavigationView
	android:id="@+id/bnv"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:background="@drawable/shape_bottom_navigation_bg"
	app:itemIconTint="@color/selector_bottom_navigation_item"
	app:itemTextColor="@color/selector_bottom_navigation_item"
	app:menu="@menu/workbenches" />

2. 自定义选中状态的图标
如果希望在选中状态下使用不同的图标
res/drawable 目录下,创建不同状态下的图标资源,例如 selector_workbenches.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 选中状态 -->
    <item android:drawable="@drawable/ic_workbenches_selected" android:state_checked="true"/>
    <!-- 未选中状态 -->
    <item android:drawable="@drawable/ic_workbenches_unselected" android:state_checked="false"/>
</selector>

res/menu/workbenches.xml 中,设置每个 itemandroid:icon 属性

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/workbenches"
        android:icon="@drawable/selector_workbenches"
        android:title="@string/workbenches" />
    <item
        android:id="@+id/personal_center"
        android:icon="@drawable/selector_personal_center"
        android:title="@string/personal_center" />
</menu>

3. 自定义选中状态的文字样式(字体颜色和字体大小)
res/values/styles.xml 文件中,添加样式

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 选中项的文本样式 -->
    <style name="TextAppearance.Active" parent="TextAppearance.AppCompat.Medium">
        <!-- <item name="android:textColor">@color/primary</item> --> <!-- 尝试设置但不生效 -->
        <item name="android:textSize">14sp</item>  <!-- 选中文本大小 -->
    </style>
    <!-- 未选中项的文本样式 -->
    <style name="TextAppearance.Inactive" parent="TextAppearance.AppCompat.Medium">
        <!-- <item name="android:textColor">@color/text</item> --> <!-- 尝试设置但不生效 -->
        <item name="android:textSize">12sp</item>  <!-- 未选中文本大小 -->
    </style>
</resources>

设置字体颜色使用 “1” 中的 app:itemTextColor="@color/selector_bottom_navigation_item"
在布局文件中,使用 app:itemTextAppearanceActiveapp:itemTextAppearanceInactiveapp:itemTextColor 属性引用上述样式和颜色选择器

<com.google.android.material.bottomnavigation.BottomNavigationView
	android:id="@+id/bnv"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:background="@drawable/shape_bottom_navigation_bg"
	app:itemTextAppearanceActive="@style/TextAppearance.Active"
	app:itemTextAppearanceInactive="@style/TextAppearance.Inactive"
	app:itemTextColor="@color/selector_bottom_navigation_item"
	app:menu="@menu/workbenches" />

三、常用的属性和方法

1. 属性和方法
BottomNavigationView 继承自 NavigationBarView

  • BottomNavigationView 常用方法
    • getMaxItemCount():返回NavigationBarView中可以显示的最大项目数。(固定值:5)
    • isItemHorizontalTranslationEnabled():返回当组合项目宽度填满屏幕时,菜单项是否在选择时水平平移。
    • setItemHorizontalTranslationEnabled(boolean itemHorizontalTranslationEnabled):设置当组合项目宽度填满屏幕时,菜单项是否在选择时水平平移。
    • setOnNavigationItemReselectedListener(BottomNavigationView.OnNavigationItemReselectedListener listener):已弃用,请使用 NavigationBarView.setOnItemSelectedListener(OnItemSelectedListener)
    • setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener listener):已弃用,请使用 NavigationBarView.setOnItemSelectedListener(OnItemSelectedListener)
  • NavigationBarView 常用方法
    • 图标(icon)相关
      • setItemIconTintList(ColorStateList tint):设置菜单项图标的不同状态(正常、选定、聚焦等)的颜色
      • setItemIconSize(int iconSize):设置菜单项图标的大小
      • setItemIconSizeRes(int iconSizeRes):设置菜单项图标的大小
    • 标签(label)相关
      • setItemTextColor(ColorStateList textColor):设置菜单项文本的不同状态(正常、选定、聚焦等)的颜色
      • setLabelVisibilityMode(int labelVisibilityMode):设置 BottomNavigationView 每一项的标签可见性模式
      • setItemTextAppearanceActive(int textAppearanceRes):设置用于被选择的菜单项标签的文本外观。
      • setItemTextAppearanceInactive(int textAppearanceRes):设置用于未选择的菜单项标签的文本外观。
      • setItemTextAppearanceActiveBoldEnabled(boolean isBold):设置被选择的菜单项标签是否为粗体
    • 指示器相关1
      • getActiveIndicatorLabelPadding():返回活动指示器容器与项目标签之间的距离
      • setActiveIndicatorLabelPadding(int activeIndicatorLabelPadding):设置活动指示器容器与项目标签之间的距离
      • getItemActiveIndicatorColor()
      • setItemActiveIndicatorColor(ColorStateList csl):设置活动指示器颜色
      • isItemActiveIndicatorEnabled()
      • setItemActiveIndicatorEnabled(boolean enabled):是否启用活动指示器
      • getItemActiveIndicatorWidth()
      • setItemActiveIndicatorWidth(int width):设置活动指示器宽度
      • getItemActiveIndicatorHeight()
      • setItemActiveIndicatorHeight(int height):设置活动指示器高度
      • getItemActiveIndicatorMarginHorizontal()
      • setItemActiveIndicatorMarginHorizontal(int horizontalMargin):设置将在活动指示器的开头和结尾保持的水平边距,确保指示器与其父容器的边缘保持给定的距离
      • getItemActiveIndicatorShapeAppearance()
      • setItemActiveIndicatorShapeAppearance(ShapeAppearanceModel shapeAppearance)2:设置项目活动指示器形状外观
    • 边距相关
      • getItemPaddingBottom()
      • setItemPaddingBottom(int paddingBottom):设置从项目标签底部到导航栏项目底部的距离。
      • getItemPaddingTop()
      • setItemPaddingTop(int paddingTop):设置从项目图标/活动指示器顶部到导航栏项目顶部的距离。
    • 背景相关
      • setItemBackground(Drawable background):将菜单项的背景设置为给定的绘图
      • setItemBackgroundResource(int resId):将菜单项的背景设置为给定的绘图
      • setItemRippleColor(ColorStateList itemRippleColor):将菜单项的背景设置为给定颜色的波纹。
    • 监听相关
      • setItemOnTouchListener(int menuItemId, View.OnTouchListener onTouchListener):为与提供的 menuItemId 关联的项目视图设置 View.OnTouchListener
      • setOnItemReselectedListener(NavigationBarView.OnItemReselectedListener listener):设置一个侦听器,当重新选择当前选定的导航项时,该侦听器将收到通知。这不需要设置“NavigationBarView.OnlitemSelectedListener”。
      • setOnItemSelectedListener(NavigationBarView.OnItemSelectedListener listener):设置一个监听器,当选择导航项时会收到通知。当重新选择当前选定的项目时,此侦听器也会收到通知,除非还设置了“NavigationBarView.setOnItemReselectedListener”。
    • 其他常用方法
      • setSelectedItemId(int itemId):设置所选菜单项ID。
      • setElevation(float elevation):设置此视图的视图的 Z 轴位置高度(像素),有阴影效果,elevation 值较大的视图会在较小的视图之上显示

2. 样式属性
在布局文件中使用到 BottomNavigationView 需要为一些必要的属性配置参数,我们也会在styles.xml和themes.xml文件中定义一些通用样式,好统一项目的风格。相信这些一定有用。

    <declare-styleable name="NavigationBarView">

        <attr name="backgroundTint" />

        <attr name="menu" />

        <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>

        <attr name="itemBackground" />

        <attr name="itemRippleColor" />

        <attr name="itemIconSize" />

        <attr name="itemIconTint" />

        <attr name="itemTextAppearanceInactive" format="reference" />

        <attr name="itemTextAppearanceActive" format="reference" />

        <attr name="itemTextAppearanceActiveBoldEnabled" />

        <attr name="itemTextColor" />

        <attr name="itemPaddingTop" format="dimension" />

        <attr name="itemPaddingBottom" format="dimension" />

        <attr name="activeIndicatorLabelPadding" format="dimension" />

        <attr name="itemActiveIndicatorStyle" format="reference" />

        <attr name="elevation" />
    </declare-styleable>

  1. Active Indicator 译为活动指示器,目前场景的显示效果为:在这里插入图片描述 ↩︎

  2. ShapeAppearanceModel 是 Android 中的一个类,主要用于控制视图的形状外观。

    • 圆角控制:设置控件的圆角半径(可以为所有角设置相同半径,也可以为不同角设置不同半径)。
    • 角形状控制:选择不同的角形状(如圆角、直角、切角)。
    • 边缘形状控制:控制视图的边缘外观。
    • 动态修改形状:使用 toBuilder() 方法动态修改现有的形状。
    • 与边框结合使用:结合 MaterialShapeDrawable 实现边框样式控制。
    • 支持多种形状:如圆形、椭圆形等。
    ↩︎
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值