【问题标题】:How to stop fragment from popping all the way back to the root fragment ? [Navigation Component]如何阻止片段一直弹出到根片段? [导航组件]
【发布时间】:2021-03-08 08:44:15
【问题描述】:

我有一个由导航组件制成的侧抽屉,当我导航到带有片段的片段并按回它时,它会将整个堆栈弹出到根片段。让我解释一下。

我从根片段导航到片段 A(这两个片段都在导航 XML 文件中定义),然后从片段 A 导航到片段 B

根片段 ---> 片段 A ---> 片段 B.

我尝试定义 menuCategory:secondary 到我的导航项,使用操作标签并在所述标签中定义“popupto”和“destination”参数,但仍然没有结果。

我们将不胜感激。

  navController = Navigation.findNavController(this, R.id.nav_host_fragment);

    if(prefsUtils.getFromPrefs(Keys.roleName).equals("PA") ||prefsUtils.getFromPrefs(Keys.roleName).equals("RSM"))
    {
        navController.setGraph(R.navigation.mobile_navigation);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_dashboard,R.id.nav_createOrder)
                .setDrawerLayout(binding.drawerLayout)
                .build();
    }

    else if (prefsUtils.getFromPrefs(Keys.roleName).equals("TP"))
    {
        navController.setGraph(R.navigation.mobile_navigation_tp);
        binding.navView.getMenu().clear();

        binding.navView.inflateMenu(R.menu.activity_main_drawer_tp);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_dashboardTP)
                .setDrawerLayout(binding.drawerLayout)
                .build();
    }

    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(binding.navView, navController);

 @Override
public void onBackPressed() {
    super.onBackPressed();
    navController.navigateUp();
}

【问题讨论】:

  • 发布您的导航图和一些代码!
  • 我已经添加了导航 UI 和 onbackpress 的代码

标签: android android-fragments navigation-drawer jitpack


【解决方案1】:

使用

findNavController().navigateUp()

避免弹出整个后台堆栈。

【讨论】:

  • 我在 onBackPressed 中使用了这个 conde,但它仍然弹回到根片段。
【解决方案2】:

您可以通过使用控制当前屏幕(片段 B)的位置

 public void onBackPressed(){


 super.onBackPressed();
startActivity(new Intent(getApplicationContext(), FragmentA.class));   


}

这里的 startActivity() 函数写入片段 A,以便在片段 B 中单击后退按钮时返回到片段 A。 将以上代码全部写在 Fragment B java 类中。

【讨论】:

  • 我有大约 10 个菜单项,然后在这些片段中包含大约 10 个片段。我不认为为这么多片段添加条件会很有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多