简体   繁体   中英

Can't pass data from one fragment to another through bundle in setGraph of navController

I am going to pass data between fragments; I'm doing this by using bundle and putting it in a setGraph argument, but I can't get it in another fragment and it always returns null. what is the problem?

Fragment Navigation

Bundle bundle = new Bundle();
bundle.putString("deviceSerialNo", "abc");
Log.d("TAGTAG", "onClick: " + bundle);
navController.setGraph(R.navigation.nav_graph, bundle);
navController.navigate(R.id.action_FirstFragment_to_SecondFragment);

Second Fragment

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        Log.d("TAGTAG", "onCreateView: " + getArguments());
        if (getArguments() != null) {
            String string = getArguments().getString("deviceSerialNo");
        }


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false);
    }

As per the setGraph() documentation , the Bundle you pass in is called startDestinationArgs :

startDestinationArgs : arguments to send to the start destination of the graph

So the only reason to use the setGraph that takes a Bundle is if your FirstFragment needs to receive a bundle for arguments. You'd need to manually pass those arguments to any other fragment, such as SecondFragment , as part of the navigate() call.

// Pass the arguments to the SecondFragment
navController.navigate(R.id.action_FirstFragment_to_SecondFragment, bundle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM