uff simon
uff simon

Reputation: 150

how to clear the fragment stack and activity stack on a button click

There are similar questions, but none of the are solving my issue. My app flow is following:

Activity home starts Activity B(which does the setup work) In activity B hosts three screens as fragments... Fragment1 -> fragment2-> fragment 3.

This is how I make fragments. I am not using replace.just adding it.

FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = null;
        if (getFragType().equals("simple")) {
            fragment = new SimpleFragment().newInstance();
        }
        if (getFragType.equals("inter")) {
            if (getFragType.getComponent().equals("con"))
                fragment = new SetupConFragment().newInstance();
            else if (getFragType.getComponent().equals("ben"))
                fragment = new SetupBenageFragment().newInstance();
        }
        fragmentTransaction.add(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
        }

Fragment3 has a done button. So once all the 3 steps are done from fragment 3 am launching a new activity C.

The issue is:-- From the activity C , if the user presses the back button, it diplays fragment 2, then fragment 1. Ideally once the user is in Activity C, back press should just exit the screen I have used all combinations of the intent flags, but it is not helping.

And this is on my button click.

Intent launch = new Intent(mContext, MainActivity.class);
                    launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    launch.putExtra("Exit me", true);
                    mContext.startActivity(launch);
                    ((ConfigureActivity)mContext).finish();

Any help will be appreciated.

Upvotes: 4

Views: 9507

Answers (3)

Hiren Patel
Hiren Patel

Reputation: 52800

You can do this way:

Clear Fragment stack:

getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 

Clear Activity stack:

Intent intent = new Intent(Your_Current_Activity.this, Your_Destination_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Hope this will help you.

Upvotes: 7

rookiedev
rookiedev

Reputation: 1127

Say, if you want to start Activity B in Activity A but you don't want user to go back to Activity A,

final Intent intent = new Intent(this, ActivityB.class);
startActivity();
finish(); // kill the current activity (i.e., Activity A) so user cannot go back

Upvotes: 2

zzas11
zzas11

Reputation: 1115

In your Activity C, you can control Back key by overriding onBackPressed().

@Override
public void onBackPressed()
{
     // code here depending on your needs
}

Upvotes: 0

Related Questions