Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android close all fragments onBackPressed

I have an activity with about 10 fragments in each fragment there is an AsyncTask with ProgressDialog I need away to close all fragments when I click back Button it's closed but the ProgressDialog still visible especially when I transfer between fragments here is the code I use

 @Override
    public void onBackPressed() {
      if(fragmentManager!=null){
            for(int i = 0; i < fragmentManager.getBackStackEntryCount(); ++i) {
                fragmentManager.popBackStack();
            }}
                                 }

also when I debug I found that it enters onCreateView for each fragment I open when I press back button although I use transaction.replace method to transfer between fragments.

like image 635
Radwa Avatar asked Nov 26 '25 14:11

Radwa


2 Answers

I am clearing stack by following method.

  public void popBackStackTillEntry(int entryIndex) {

    if (getSupportFragmentManager() == null) {
        return;
    }
    if (getSupportFragmentManager().getBackStackEntryCount() <= entryIndex) {
        return;
    }
    FragmentManager.BackStackEntry entry = getSupportFragmentManager().getBackStackEntryAt(
            entryIndex);
    if (entry != null) {
        Utilities.sDisableFragmentAnimations = true;
        getSupportFragmentManager().popBackStackImmediate(entry.getId(),
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }


}

Clear upto 1 means all fragments will be removed from stack and only single fragment will remain in stack.

Usage popBackStackTillEntry(1);

like image 120
Faraz Ahmed Avatar answered Nov 28 '25 03:11

Faraz Ahmed


This is my kotlin solution:

override fun onBackPressed() {
   supportFragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}

You can pass null for the name as it is nullable.

like image 37
Top4o Avatar answered Nov 28 '25 05:11

Top4o



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!