Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synthesize Android fragment backstack

I have an activity that uses fragments to change views instead of launching new activities. Lets say I have 3 fragments A, B and C. When the application launches the default fragment is set to A. The user can click a button on A to transition to B -- same with B to C.

Therefore the backstack looks like: [A] -> [B] -> [C]

What I need to do is deep link directly to fragment C from a notification while still building out the backstack so that when the activity is launched. Fragment C should be displayed while allowing the user to click the back button to get back to views B and A respectively.

like image 627
Greg Marut Avatar asked Aug 30 '26 02:08

Greg Marut


1 Answers

You can make 3 separate transactions. This is a lot more natural than manually checking the state of the backstack.

@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    showFragmentA();

    if (getIntent().hasExtra("some_deep_link_flag")) {
        showFragmentB();
        showFragmentC();
    }
}

private void showFragmentA() {
    Fragment a = new Fragment();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, a)
            .addToBackStack(null)
            .commit();
}

private void showFragmentB() {
    Fragment b = new Fragment();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, b)
            .addToBackStack(null)
            .commit();
}

private void showFragmentC() {
    Fragment c = new Fragment();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, c)
            .addToBackStack(null)
            .commit();
}

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!