How can I call OnActivityResult inside Fragment an

2019-03-15 02:08发布

问题:

I want to know is it possible on onActivityResult()to use inside Fragment and if yes then how it works please explain with example.

回答1:

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


回答2:

Definitely it will work, It will work same like in activities. You have call startActivityForResult(intent, requestCode); and normally get result in

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


回答3:

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
}

now you call onActivityResult like this

getActivity().startActivityForResult(). 

EDIT

The Above answer is old

check here the updated answer https://stackoverflow.com/a/17085889/7666442



回答4:

Use this code in the 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);
    }
}


回答5:

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

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

How is works

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

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

if your fragment in ViewPager desired fragment index is found using

requestCode>>16

and requestCode is found by requestCode&0xffff.