使用NavHostFragment、navigation--- avtivity向fragment传值,fragment之间传值
avtivity向fragment传值 (只是向最顶上的那个fragment传值)
fragment接收activity传过来的值
//我要传的值是Bundle val bundle = Bundle() bundle.putString("type", "我要传的值") val controller = Navigation.findNavController(this, R.id.mine_elder_f) //获取Navigation的NavGraph val graph = controller.graph //set值 val argument = NavArgument.Builder() .setDefaultValue(bundle) .build() //放到NavGraph中 graph.addArgument("type", argument)
val map=NavHostFragment.findNavController(this).graph.arguments //这里接收的type和graph.addArgument("type", argument) 相对应 val navArgument = map["type"] //接收到了传过来的Bundle val bundle = navArgument?.defaultValue as Bundle //在获取Bundle中的值 type = bundle.getString("type")
fragment与fragment之间传值
fragmentA向fragmentB传值分为两种:一种就是两个fragment同属于一级用parentFragmentManager传值;另一种两个fragment是包含关系用childFragmentManager进行传值;(下面的例子是属于两个fragment属于同一级的)
//传值fragment val bundle = Bundle() bundle.putString("name", name) parentFragmentManager.setFragmentResult("30", bundle)
接收:
parentFragmentManager.setFragmentResultListener( "30", this, FragmentResultListener { requestKey, result -> name = result.getString("name").toString() })