android-fragments 从活动调用片段的onActivityResult以将数据传递给片段,不推荐使用此方法

o8x7eapl  于 2022-11-13  发布在  Android
关注(0)|答案(1)|浏览(168)

我尝试以下面的方式将在Activity中接收到的数据传递到fragment

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    myFragment.onActivityResult(requestCode, resultCode, data)
}

但是,myFragment.onActivityResult(requestCode, resultCode, data)已经过时了。我如何在不使用过时代码的情况下将数据发送到片段级别?

w9apscun

w9apscun1#

您必须使用片段侦听器来代替。如下所示:

parentFragmentManager.setFragmentResultListener(
                "YOUR_REQUEST_KEY",
                viewLifecycleOwner
            ) { requestKey, result ->
                if (requestKey == "YOUR_REQUEST_KEY") {
                    //Do whatever you could previously do in this section in onActivityResult
                }
            }

当您要设置结果时,请执行以下操作:

val bundle = Bundle()
    //Put your data in bundle here
    setFragmentResult("YOUR_REQUEST_KEY", bundle)

相关问题