Niraj Kumar
Niraj Kumar

Reputation: 49

How to prevent application closed on pressing device back button?

I am developing application in which I have three fragment A,B,C, when I press on some button in A it navigate to b Thats fine ,and when I press device back button application closes instead of going to A,How can I prevent this problem .

Upvotes: 2

Views: 1428

Answers (4)

jigspatel
jigspatel

Reputation: 410

// Your Main Activity // Override OnBackPressed Event Which as below

 @Override
    public void onBackPressed() {

        if (getSupportFragmentManager()
                .getBackStackEntryCount() > 0) {

            super.onBackPressed();

        } else {

            UIUtils.showAlertDialog(this, getString(R.string.app_name), "Are you sure want to Exit App?", false);

        }
}

Upvotes: 2

Rahul
Rahul

Reputation: 510

Please add

addToBackStack(null); 

to your FragmentTransaction object if you not added when replacing or adding fragments.

it will autamatically maintain backstacks on Backpress.

Hope it will help you !

Upvotes: 0

Camilo Ortegón
Camilo Ortegón

Reputation: 3702

You should override onBackPressed() method. There you can choose what action to do when this happens. If you still want to finish the activity in some cases, you can call finish() method.

Upvotes: 0

Frosty
Frosty

Reputation: 500

Just override the activity's onBackPressed() function according to your need.

Upvotes: 0

Related Questions