了解我们从哪个片段导航的最佳方式

The best way to know which fragment we navigated from

我正在编写一个使用大量片段(带有 ViewModel)的应用程序。我将导航组件与导航图一起使用,通过使用

从一个片段导航到另一个片段

findNavController().navigate(R.id.myFragment)

在某些情况下,我经常浏览片段并且没有任何静态依赖性。
你可以按 F1->F2->F3->F4 也可以按 F1->F2->F4->F3

例如,当我们导航到 F4 时,我需要知道之前是哪个片段,是 F3 还是 F2? 我现在设法通过向 F4 发送带有 arguments.putBoolean("fromFragment3",true)arguments.getBoolean("fromFragment3")arguments Bundle() 来解决问题,但这看起来很难看,你很快就会搞砸整个代码。

问题:

在导航到当前片段之前了解用户是哪个片段的最佳方法是什么?

您可以使用 addOnDestinationChangedListener 并侦听片段事务:

 NavController navController= Navigation.findNavController(MainActivity.this,R.id.your_nav_host);

        navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                Log.e(TAG, "onDestinationChanged: "+destination.getLabel());
            }
        });