4

I am overriding the onBackPressed method in activity:

 @Override
public void onBackPressed() {
    super.onBackPressed();
}

And I am adding up fragments as follows:

    fragmentManager.beginTransaction()
                .add(R.id.frame_container, myFragment).addToBackStack("").commit();

The problem is my onBackPressed is not getting called in the activity. But when I change it to :

replace(R.id.frame_container, myFragment).addToBackStack("").commit();

it gets called as expected. I have to add the fragments. How to solve this issue?

pagalpanda
  • 150
  • 2
  • 16

1 Answers1

4
@Override
public boolean onKeyUp(int keyCode, KeyEvent objEvent) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
        return true;
    }
    return super.onKeyUp(keyCode, objEvent);
}

@Override
public void onBackPressed() {

    goBack();
}

public void goBack() {

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            MyCaseActivity.this);

    alertDialog.setTitle("");
    alertDialog.setMessage("Are you sure you want to exit?");

    alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    System.exit(0);
                }
            });

    alertDialog.setNegativeButton("NO",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

This works for me.

Pang
  • 9,564
  • 146
  • 81
  • 122
akhil batlawala
  • 1,066
  • 1
  • 10
  • 30