user2991952 user2991952 - 2 months ago 21
Android Question

how to Get behaviour of super.onbackpressed() within overrided onbackpressed()

I was tried to go back with confirmation dialog so that i was decided to handle onbackpressed() and then i had put my code for confirm dialog with ok and cancel button for null listener.



@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirmation");
builder.setMessage("Are you sure want to exit?");
builder.setPositiveButton("OK",null);
builder.setNegativeButton("Cancel", null);
builder.show();
}



It was worked fine but the problem is if i click ok but it should continue for behaviour of super.onbackpressed() otherwise it should be in same activity.


the following code that i had tried.



@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirmation");
builder.setMessage("Are you sure want to exit?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
//super.onBackPressed();
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}

Answer

put finish() to finish your activity in onclick of positive button ...

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        //super.onBackPressed();
        finish();
    }
});