Raju Gujarati Raju Gujarati - 1 month ago 6x
Android Question

Fragment pressing back button

I am now having an activity containing fragments

[1] , [2] , [3] , [4]

If pressing buttons , [3] , it can be redirected to [4]

I would like to implement the back button as shown follow..

when pressing back at [4] , it return to [3]

when pressing back at [3] , it return to [2]

when pressing back at [1] , the activity finishes();

When it comes to the current implementation, it finish the activity instead of popping up the Fragment. Would you please tell me what I should do or keep in mind ?

public boolean onKeyDown(int keyCode, KeyEvent event) {

if( keyCode==KeyEvent.KEYCODE_BACK)


return super.onKeyDown(keyCode, event);



This is a working solution for me:

dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            // DO WHAT YOU WANT ON BACK PRESSED
                            return true;
                        return false;