OnActivityResult 未在 Fragment 中调用,其中意图从适配器类传递 [英] OnActivityResult not getting called in Fragment where intent pass from adapter class
问题描述
所以在我的适配器类中,我想允许用户捕获图像
So in my adapter class, I would like to allow user to capture image
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")
}
我希望片段类中的 onActivityResult
被调用,但它没有.
I want the onActivityResult
in a fragment class get called, but it doesn't.
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")
}
}
没有显示吐司.如何解决?
There are no toast displayed. How to solve ?
我意识到 onActivityResult
如果我放入我的一个 Activity 类就可以工作,但我想放入 Fragment 类!
I realize the onActivityResult
works if I put in one of my Activity class, but I want to put at Fragment class !
推荐答案
正如 nikita 所说,如果你想在片段中获得结果,你应该从片段中调用 startActivityForResult
.
as nikita said you should call startActivityForResult
from fragment if you want to get results in fragment.
我想在适配器类中调用 startActivityForResult,所以我会需要上下文作为活动然后创建 OnItemClick 接口,使您的片段实现它并将其在构造函数中传递给您的适配器.然后当用户点击某个item时调用接口方法
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)
}
这篇关于OnActivityResult 未在 Fragment 中调用,其中意图从适配器类传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!