Search code examples
androidandroid-fragmentsfragment-backstackfragmentmanager

Manage Fragment Backstack Flow without flicks


  1. I have created an AppCompatActivity Opened fragment A->B->C->D->E->F with replace()
  2. I am on F which contain button when I press the button I want to clear Fragments up to C and Want to open G on top of C so new Sequence will be A->B->C->G.I can do this with popBackStackImmediate() and add G on top of C with replace function.

Problem: When I press the button I see C for fraction of seconds and then G Is displayed on it.To Prevent this I tried to stop the animations with help of answer but C still visible for fraction of seconds even when the animation is stopped for fragments.

Is there any better way we can design fragment flow or way to solve this flicks when replacing fragment on top of C?


Solution

  • I was so curious about this question that i created a sample project and implemented the same use-case that you mentioned in your question. Here is how i handled this.

    Used this method to remove F,E,D fragments from backstack

    private void removeFragments() {
        getSupportFragmentManager().popBackStack("F", FragmentManager.POP_BACK_STACK_INCLUSIVE);
        getSupportFragmentManager().popBackStack("E", FragmentManager.POP_BACK_STACK_INCLUSIVE);
        getSupportFragmentManager().popBackStack("D", FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
    

    Used this method to replace fragment

    private void replaceNewFragment(String key) {
        getSupportFragmentManager().beginTransaction().addToBackStack(key)
                .replace(android.R.id.content, AFragment.newInstance(key)).commit();
    }
    

    Here is a video demo video. enter image description here

    Here is complete of this project on github