Where should onActivityResult be handled, dialog fragment, fragment, or activity?

匆匆过客 提交于 2019-11-30 09:52:36

问题


In my android app, I have a fragment where the user can add a picture, either from gallery or from camera. I've created an alert dialog and placed it in a DialogFragment. When the user chooses an option, I call startActivityForResult. My question is, where should ideally this result be handled? (i.e. where should i place onActivityResult?) In the DialogFragment class, the host fragment, or the host activity? Does it matter?


回答1:


onActivityResult() will be invoked first on the Activity. After that it will be reached out to the Fragments, if you call super.onActivityResult() in your Activity.

This is because of the modular design of Fragments. If a result comes in, the Activity handles it and the unhandled results, if any, can be reached out to the Fragments.

To answer your question: Decide where it makes sense to handle the results in respect of your app design / code. If you handle it in the Fragment and send the results back to the Activity through a callback f.e., you can handle it directly in the Activity.




回答2:


You must write onActivityResult() in your HostActivity.Java as follows:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  //do something
}



回答3:


Yes, it does matter; It is the activity that receives the result, based on that result you decide what actions to take further, notify your fragments or whatever is that you need.



来源:https://stackoverflow.com/questions/19518826/where-should-onactivityresult-be-handled-dialog-fragment-fragment-or-activity

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