android – OnActivityResult未在Fragment中调用,其中intent从适配器类传递
作者:互联网
所以在我的适配器类中,我想允许用户捕获图像
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,但事实并非如此.
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类,但我想放在Fragment类!
解决方法:
正如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)
}
标签:onactivityresult,android,kotlin,android-intent 来源: https://codeday.me/bug/20190930/1834329.html