menu 菜单

(其实很少用系统的菜单,通常都是自己写,下方菜单的图标自己设置动画[底部标签的动画自己设置])

创建 menu 菜单
res –> New –> New Resource Directory –> menu
menu –> Menu Resource File

id :对应 Fragment 的 id
icon :图标资源
title :标题
showAsAction : 控制菜单项在导航栏上展示位置

  • always - 总是在导航栏上显示菜单图标
  • ifRoom - 如果导航栏右侧有空间,该项就直接显示在导航栏上,不再放入溢出菜单
  • never - 从不在导航栏上显示,一直放在溢出菜单列表中(不显示图标,显示三个点,点击仨点显示下拉菜单)
  • collapseActionView
  • with Text - 如果能在导航栏上显示,除了显示图标还要显示该项的文字说明
    iconTint :修改图标颜色
1
2
3
4
5
6
7
8
<menu xmlns:android="http://schemas.android.com/apk/res/androxmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/homeFragment"
android:icon="@drawable/ic_home"
android:title="Home"
app:showAsAction="always"
android:iconTint="#009688"/>
</menu>

用一个控件 BottomNavigationView 显示底部菜单

底部标签栏只有一个,显示在 Activity 上

activity_main.xml 中
添加一个控件
BottomNavigationView 底部导航栏

  • app:menu=”@menu/bottom_menu”
1
2
3
4
5
6
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layoutheight="wrap_content"
app:menu="@menu/bottom_menu"/>
</androidx.constraintlayout.widget.ConstraintLayout>

实现关联 切换

BottomNavigationView 是没有切换能力的,仅做展示,只是有点击效果
需要将 BottomNavigationView 和 NavController 关联

在 MainActivity 中让 bottomNavigationView 和 NavController 关联
setupWithNavController

1
2
3
4
val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
val navController = navHostFragment.navController

binding.bottomNavigationView.setupWithNavController(navController)

设置堆栈

在没有 action 线的情况下如何设置堆栈(不能任其按返回键返回)

监听器
setOnItemSelectedListener 在 item 由未选中到选中状态时触发
setOnItemReselectedListener 在 item 处于选中状态再次点击时触发

有返回值 true、false 被点击是后是否可以选中

(setOnItemSelectedListener 会同时把事件拦截了 还要设置将对应按钮导航到对应栏目) 把这个事件拦截了,具体做什么事情要告诉系统

1
2
3
4
5
6
7
8
9
10
11
12
13
binding.bottomNavigationView.setOnItemSelectedListener { menultem ->
//清空栈信息(把栈里的东西弹出来)

navController.popBackStack() //点一个就清一个栈

when(menultem.itemld){
R.id.homeFragment-> navControllernavigate(R.id.homeFragment)
R.id.welcomeFragment -> navController.navigate(R.id.welcomeFragment)
R.id.quideFragment-> navController.navigate(Rid.quideFragment)
R.id.drawFragment-> navController.navigate(R.id.drawFragment)
}
true
}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2023-2025 Annie
  • Visitors: | Views:

嘿嘿 请我吃小蛋糕吧~

支付宝
微信