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

眉间皱痕 提交于 2019-12-29 02:11:06

问题


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")
    }

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 ?

I realize the onActivityResult works if I put in one of my Activity class, but I want to put at Fragment class !


回答1:


as nikita said you should call startActivityForResult from fragment if you want to get results in fragment.

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,...)
    }

}

And in your adapter

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



回答2:


If you want fragment's onActivityResult() to be called, call startActivityForResult(intent, id) from fragment, not from activity (try pass fragment reference to adapter).

Also, make sure you haven't overridden activity's onActivityResult() or call super.onActivityResult() in activity.



来源:https://stackoverflow.com/questions/54685955/onactivityresult-not-getting-called-in-fragment-where-intent-pass-from-adapter-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!