OnActivityResult not getting called in Fragment wh

2020-02-07 13:11发布

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 !

2条回答
▲ chillily
2楼-- · 2020-02-07 13:35

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)
}
查看更多
该账号已被封号
3楼-- · 2020-02-07 13:42

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.

查看更多
登录 后发表回答