通过NavigationComponent在BottomNavigation片段之间传递数据

时间:2019-12-31 05:22:55

标签: java android android-fragments navigation bottomnavigationview

是否可以通过NavigationContoller在BottomNavigation控制的片段之间传递Parcelable对象/参数?

这是我的应用程序的流程,用户登录到应用程序,然后打开一个包含BottomNavigation的片段。我能够将参数传递给第一个片段(使用NavHostFragment.findNavController(this).navigate(action)打开第一个片段),我能够向该操作添加参数并传递值,但是BottomNavigation没有任何导航指令,可以通过menuID进行导航。如何通过捆绑包在所有这些底部导航的片段之间传递登录用户参数。

我尝试使用onDestinationChanged()传递参数

@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
        NavArgument argument = new NavArgument.Builder().setDefaultValue(selectedUser).build();
        destination.addArgument("user", argument);
}

但应用仍因java.lang.IllegalArgumentException: Required argument "user" is missing and does not have an android:defaultValue崩溃

3 个答案:

答案 0 :(得分:1)

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    
    navController = Navigation.findNavController(getActivity(), R.id.navBottomNavigation);
    NavigationUI.setupWithNavController(R.id.bottomNavigationView, navController);
    NavGraph navGraph = navController.getNavInflater().inflate(R.navigation.nav_sub_graph);

    NavArgument argument = new NavArgument.Builder().setDefaultValue(yourObject).build();
    navGraph.addArgument("yourObject",argument);

    navController.setGraph(navGraph);
}
在BottomNavigation中传递对象嵌套的片段

 navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
        @Override
        public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {

            switch (destination.getId()) {
                case R.id.profileFragment:
                    NavArgument argumentProfile = new NavArgument.Builder().setDefaultValue(preferences).build();
                    destination.addArgument("preferences",argumentProfile);

                case R.id.homeFragment:
                    NavArgument argumentHome = new NavArgument.Builder().setDefaultValue(preferences).build();
                    destination.addArgument("preferences",argumentHome);

                case R.id.orderFragment:
                    NavArgument argumentOrder = new NavArgument.Builder().setDefaultValue(preferences).build();
                    destination.addArgument("preferences",argumentOrder);
            }
        }
    });

答案 1 :(得分:0)

您还可以在他们引用的导航文档SharedViewModel中使用Pass data between destinations

通常,您应该强烈建议只传递最小的金额 目的地之间的数据量。例如,您应该将密钥传递给 检索对象而不是传递对象本身,作为总数 在Android上,所有已保存状态的空间都受到限制。如果您需要通过 大量数据,请考虑使用ViewModel中所述 在片段之间共享数据。

答案 2 :(得分:0)

我们可以使用asad所述的用户SharedViewModel,也可以使用NavGraph设置参数

navController.getGraph()。findNode(R.id.todoFragment) .addArgument(“ user”,新的NavArgument.Builder() .setDefaultValue(用户) .build());