Call Onresume When Back Button Pressed When Using Fragments
Solution 1:
I am posting late answer, but i think this will be useful for others
While we are using add()
with Fragment transactions, onResume()
will not be called on Source fragment. Only Destination fragment will get onResume()
callback
But using this way, we can achieve onResume()
callback to Source fragment :
Add this in Host Activity's onBackPressed()
@Override
public void onBackPressed() {
getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getBackStackEntryCount() - 1).onResume();
super.onBackPressed();
}
Note : Be sure that you have called addToBackStack()
with commit()
This code will give onResume()
callback to Source fragment
Thank you
Solution 2:
instead of calling "add" for the second fragment use "replace instead"
i.e. instead of
ft.add(R.id.content_fragment, fragment, "Home");
use
ft.replace(R.id.content_fragment, fragment, "Home");
So whenever u will press back button to go previous fragment, the first fragment's lifecycle will be called back again.
OR if it doesnt meet ur requirement, u can do this:
privatefinalstaticStringTAG_FRAGMENT="TAG_FRAGMENT";
privatevoidshowFragment() {
finalMyfragmentfragment=newMyFragment();
finalFragmentTransactiontransaction= getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
transaction.addToBackStack(null);
transaction.commit();
}
@OverridepublicvoidonBackPressed() {
finalMyfragmentfragment= (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or notsuper.onBackPressed();
}
}
Solution 3:
i am using this method for all my fragment a
// For the Fragment Replace And AddtobackStackvoidreplaceFragment(Fragment fragment) {
StringbackStateName= fragment.getClass().getName();
StringfragmentTag= backStateName;
FragmentManagermanager=this.getSupportFragmentManager();
booleanfragmentPopped= manager
.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
// fragment not in back stack, create it.FragmentTransactionft= manager.beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
Solution 4:
If you are adding fragment
ft.add(R.id.content_fragment, fragment, "About");
then it'll not call any method of first fragment on back press.
To call the method of the first fragment, instead replace the fragment with :
ft.replace(R.id.content_fragment, fragment, "About");
But this will call onCreateView()
first then other methods.It is not possible in fragment on backpressed to call onResume()
, as in activity happens
Post a Comment for "Call Onresume When Back Button Pressed When Using Fragments"