Skip to content Skip to sidebar Skip to footer

Android - How Can I Return The Current Fragment After Onactivityresult()?

I have an activity that have some buttons and some fragments. If I click on button A, i'll show Fragment 'FragA'. When I'm in 'FragA', I can perform some actions like choose a pic

Solution 1:

You can recreate fragment again and replace it in your Activity with using modification of this code:

if (currentState == STATE_MAIN_FRAGMENT) {
        return;
}
mainScreenFragment = (MainScreenFragment) getSupportFragmentManager().findFragmentByTag(MainScreenFragment.TAG);
if (mainScreenFragment == null) {
    mainScreenFragment = newMainScreenFragment();
}
FragmentTransactionfragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flFragmentContainer, mainScreenFragment, MainScreenFragment.TAG);
fragmentTransaction.commit();

First "if" checks if the fragment is set or not. It is not required but it's a good practice. It prevents you from replacing fragment when it is not necessary.

And there is one thing strange for me. Because you said <<"FragA" is hidden>> - that means it was already set but container is not visible? Then yourFragmentContainer.setVisiblity(View.VISIBLE); in on Activity result.

And the last thing that could help you is to retain the fragment so it won't be ever destroyed and recreated again. Some helpful links:

Understanding Fragment's setRetainInstance(boolean)

http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)


Or you can just copy-paste what is in your Button's OnClickListener so it happens onActivityResult too.

Post a Comment for "Android - How Can I Return The Current Fragment After Onactivityresult()?"