How can I call OnActivityResult inside a fragment and how does it work?

I want to know if it is possible to use Fragment inside onActivityResult() , and if so, how it works, please explain with an example.

+19
source share
6 answers

You would call:

 startActivityForResult(i, 1); 

and then:

 @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { //super.onActivityResult(requestCode, resultCode, data); comment this unless you want to pass your result to the activity. } 
+20
source

Use this code in activity.

 public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag(childTag); if (fragment != null) { fragment.onActivityResult(requestCode, resultCode, intent); } } 
+3
source

Definitely it will work, it will work the same way as in actions. You call startActivityForResult(intent, requestCode); and usually get the result in

 @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } 
+3
source

Yes, you can use OnActivityResult inside Fragment. Like this

 public void onActivityResult(int requestCode, int resultCode, Intent intent) { //super.onActivityResult(requestCode, resultCode, intent); // perform your action here } 

EDIT

Check out this old question for more info.

fooobar.com/questions/54702 / ...

+2
source

if you call startActivityForResult() in the fragment, the result is delivered to the parent activity.

 public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent);//will deliver result to desired fragment. } 

How does it work

if you see requestCode in action, it will be like 655545, now

super.onActivityResult () will calculate the desired fragment and request code.

if your fragment in the list of the desired ViewPager fragment is found using

 requestCode>>16 

and requestCode is requestCode&0xffff .

+1
source

Source: https://habr.com/ru/post/1268967/


All Articles