Android Material 常用组件详解(七)—— BottomNavigationView 使用详解

一、前言

在开发中,底部导航栏十分常见。一般来说,我们可以自己组合控件实现,比如LinearLayout + TextView(使用android:drawableTop属性+selector状态切换)、RadioGroup + RadioButton等等组合控件的方法自定义实现复杂效果。而BottomNavigationView控件也是一种不错的选择。
在这里插入图片描述

二、实现方式

2.1 基础使用

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
  ...
  <com.google.android.material.bottomnavigation.BottomNavigationView
      android:id="@+id/bottom_navigation"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:menu="@menu/bottom_navigation_menu" />

</LinearLayout>

在menu目录的bottom_navigation_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_dashboard"
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="@string/title_dashboard" />

    <item
        android:id="@+id/navigation_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_notifications" />

</menu>

注意: BottomNavigationView不支持超过5个menu项目。

设置一个侦听器,该侦听器在选择底部导航项时将得到通知。除非还设置了{@link OnNavigationItemReselectedListener},否则当重新选择当前选择的项目时,也会通知此侦听器。

BottomNavigationView.setOnNavigationItemSelectedListener {
    item ->
    when(item.itemId) {
   
        R.id.item1 -> {
   
            // Respond to navigation item 1 click
            true
        }
        R.id.item2 -> {
   
            // Respond to navigation item 2 click
            true
        }
        else -> false
    }
}

设置一个侦听器,当重新选择当前选择的底部导航项时将通知该侦听器。

bottomNavigation.setOnNavigationItemReselectedListener {
    item ->
    when(item.itemId) {
   
        R.id.item1 -> {
   
            // Respond to navigation item 1 reselection
        }
        R.id.item2 -> {
   
            // Respond to navigation item 2 reselection
        }
    }
}

2.2 添加未读提示

	
  • 10
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值