OnActivityResult 未在意图从适配器传递的 Fragment 中被调用 class

OnActivityResult not getting called in Fragment where intent pass from adapter class

所以在我的适配器 class 中,我想允许用户捕获图像

 fun dispatchTakePictureIntent() {
        try {
            val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            (context as Activity).startActivityForResult(captureIntent, 1)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
        }
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        Log.d("MyAdapter", "onActivityResult")
    }

我希望片段 class 中的 onActivityResult 被调用,但它没有。

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        val imageListAdapter : ImageListAdapter?=null
        imageListAdapter?.onActivityResult(requestCode, resultCode,data)
                if (requestCode == 1 && resultCode == Activity.RESULT_OK) 
                {
                    longToast("called")
                }else{
                    longToast("no")
                }
            }

没有显示吐司。如何解决?

我意识到 onActivityResult 如果我放入我的 Activity class 之一,但我想放入 Fragment class !

如果要调用片段的 onActivityResult(),请从片段而不是 activity 调用 startActivityForResult(intent, id)(尝试将片段引用传递给适配器)。

此外,请确保您没有覆盖 activity 的 onActivityResult() 或在 activity 中调用 super.onActivityResult()

正如 nikita 所说,如果您想在片段中获得结果,您应该从片段中调用 startActivityForResult

I want to call startActivityForResult in adapter class, so I would need context as Activity Then create OnItemClick interface make your fragment implement it and pass it in a constructor to your Adapter. Then when a user clicks on an item call interface method

interface OnItemClickListener{
   onClick(item:T)
}

Foo: Fragment, OnItemClickListener{
...
    onClick(item:T){
        startActivityForResult...
    }
...
    initAdapter(){
        Adapter(listener=this,...)
    }

}

在你的适配器中

...
itemView.setOnClickListener{
    listener.onClick(item)
}