导航组件,控制何时显示汉堡包或返回图标 [英] Navigation Component, Control when to show hamburger or back icon

查看:38
本文介绍了导航组件,控制何时显示汉堡包或返回图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下活动

class MainActivity : AppCompatActivity() {

private lateinit var drawerLayout: androidx.drawerlayout.widget.DrawerLayout

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)

    drawerLayout = drawer_layout

    val navController = Navigation.findNavController(this, R.id.fragment_main_navHost)

    setSupportActionBar(toolbar)

    NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
    navView_main.setupWithNavController(navController)
}

override fun onSupportNavigateUp(): Boolean {
    return NavigationUI.navigateUp(drawerLayout,
        Navigation.findNavController(this, R.id.fragment_main_navHost))
}

override fun onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START)
    } else {
        super.onBackPressed()
    }
}

如您所见,它与导航图相关联,而我正在使用导航抽屉.当我浏览抽屉中的项目时,我想保留汉堡包图标,并且仅当我单击片段或弹出窗口中的项目时才将其更改为向上/后退按钮,并确保系统的行为反映了什么用户期望基于显示的图标.可以吗

which as you can see is associated with navigation graph, and I am using a navigation drawer. When I am navigating through the items in the drawer I want to keep the hamburger icon, and only change it to up/back button when I click on an item within the fragment or popup for example and ensure that the behavior of the system reflects what the user expects based on the icon displayed. Is that possible

推荐答案

要控制AppBar导航何时向上/向后显示需要做以下工作

To control when the AppBar navigation up/back show the following need to be done

1- 创建 AppBarConfiguration 并将顶级目标和 drawerLayout 传递给它

1- create AppBarConfiguration and pass to it the top level destination and drawerLayout

    appBarConfiguration = AppBarConfiguration(
        setOf(
            R.id.dest_one,
            R.id.dest_two
        ),
        drawerLayout
    )

2- 告诉 AppBar 有关配置和导航的信息.这将有助于显示标题并显示箭头或抽屉菜单图标

2- Tell the AppBar about the configration and navigation. this will help to show a title and show up arrow or drawer menu icon

setupActionBarWithNavController(navController, appBarConfig)

3- 最后覆盖 onOptionsItemSelected 和 onSupportNavigateUp 以及导航组件扩展,以通知 AppBar 如何表现

3- Finally override the onOptionsItemSelected and onSupportNavigateUp and the Navigation Component extension to inform the AppBar how to behave

    override fun onOptionsItemSelected(item: MenuItem)= item.onNavDestinationSelected(findNavController(R.id.my_nav_host_fragment))
        || super.onOptionsItemSelected(item)


override fun onSupportNavigateUp() = findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration)

参考 Google 代码实验室导航 导航代码实验室

Reference Google Code Lab Navigation Navigation Codelab

这篇关于导航组件,控制何时显示汉堡包或返回图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆