我有以下活动

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()
    }
}

正如你们所看到的,它与导航图有关,我使用的是一个导航抽屉.当我浏览抽屉中的物品时,我想保留汉堡包图标,仅当我点击片段或弹出窗口中的物品时,才将其更改为向上/后退按钮,并确保系统的行为根据显示的图标反映用户的期望.有可能吗

推荐答案

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

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有关配置和导航的信息.这将有助于显示标题和向上箭头或抽屉菜单图标

setupActionBarWithNavController(navController, appBarConfig)

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)

Reference Google Code Lab Navigation Navigation Codelab

Kotlin相关问答推荐

Criteria Api 中的 Kotlin 泛型

使用调度程序运行异步 Kotlin 代码

按钮无法在 Android Studio 上打开新活动

如何连接两个 kotlin 流?

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

这是什么 Kotlin 类型:(String..String?)

类型不匹配:Required: Context, Found: Intent

Kotlin 代码是如何编译成原生代码的?

Kotlin - 当表达式返回函数类型

类型是什么意

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

参考 Kotlin 中的 Java 接口静态字段

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

在用Kotlin编写的Android库公共API中处理R8+JvmStatic Annotation+Lambda

Kotlin的web-framework框架

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

Kotlin数据类打包

如何在kotlin用mockito模仿lambda

用 kotlin 学习 Android MVVM 架构组件

从 java 活动 *.java 启动 kotlin 活动 *.kt?