android-fragments 用于具有多个片段的单个活动的“后退”按钮

to94eoyn  于 2022-11-14  发布在  Android
关注(0)|答案(3)|浏览(150)

使用jetpack导航,单个Activity具有多个片段。通过导航图中定义的操作从主片段导航到另一个片段后,汉堡菜单图标保持不变,它没有更改为后退箭头按钮。
如何将这个汉堡菜单图标更改为后退箭头按钮?当单击时,它应该返回到主片段。
在Android Studio中创建一个新项目,并选择Navigation Drawer Activity作为模板,将使用上述3个片段设置单个Activity。

w3nuxt5m

w3nuxt5m1#

只需将此添加到根Activity中。

if (supportFragmentManager.backStackEntryCount > 0) {
  supportActionBar!!.setDisplayHomeAsUpEnabled(true)
  toolbar.setNavigationOnClickListener {
      if (supportFragmentManager.backStackEntryCount > 0) {
          super.onBackPressed()
      } else {
          supportActionBar!!.setDisplayHomeAsUpEnabled(false)
          drawerLayout.addDrawerListener(toggle)
          toggle.syncState()
          drawerLayout.openDrawer(GravityCompat.START)
      }
  }
} else {
  supportActionBar!!.setDisplayHomeAsUpEnabled(false)
  drawerLayout.addDrawerListener(toggle)
  toggle.syncState()
}
uubf1zoe

uubf1zoe2#

在您的活动中尝试此操作

NavigationView nav_view = (NavigationView) findViewById(R.id.nav_view);
          drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);

        appBarConfiguration =
                new AppBarConfiguration.Builder(navController.getGraph()).build();
        setupActionBarWithNavController(this, navController,appBarConfiguration);
        NavigationUI.setupWithNavController(nav_view, navController);
        NavigationUI.setupActionBarWithNavController(this, navController);
        NavigationUI.setupActionBarWithNavController(this, navController, drawer);
ikfrs5lh

ikfrs5lh3#

我在AppBarConfiguration中设置了多个片段。

appBarConfiguration = AppBarConfiguration(
    setOf(
        R.id.nav_main, R.id.nav_detail
    ), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)

由于详细信息片段是在AppBarConfiguration中设置的,因此当从主片段导航到详细信息片段时,汉堡菜单图标保持不变,因为详细信息片段被设置为drawerlayout之一。
从AppBarConfiguration中删除R.id.nav_detail后,导航到detail片段,汉堡菜单图标将自动更改为带有DrawerArrowDrawable动画的后退箭头图标。

appBarConfiguration = AppBarConfiguration(
    setOf(
        R.id.nav_main
    ), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)

相关问题