基于Navigation和Bundle完成两个Fragment中参数的传递

309 阅读1分钟

使用Fragment的时候可能需要在两个Fragment之间进行参数的传递,可以将数据存入bundle,在页面导航时,传入bundle,完成参数的传递。具体实现如下:

1.初始化导航控制器

NavController controller = Navigation.findNavController(requireView());

2.创建Bundle对象

Bundle bundle = new Bundle();
bundle.putString("key", "this is value");

类似的还存在 putInt、putChar等方法

3.传递参数

controller.navigate(R.id.action_nav_home_to_nav_laboratory, bundle);

4.接受参数

在跳转的页面使用getArguments()方法可以获取传入的Bundle对象,通过之前的 key 取出相关值即可。

 Bundle bundle = getArguments();
 String str = bundle.getString("key");

为了避免空指针错误,此处可以添加默认值

String str = bundle.getString("Key","null");