Friday, September 29, 2017

Display Alert Dialog when Back button press- android studio




@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {

    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        AlertDialog.Builder alertbox = new AlertDialog.Builder(MainActivity.this);
        alertbox.setIcon(R.drawable.just);
        alertbox.setTitle("You Want To Exit");
        alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                // finish used for destroyed activity                finish();
            }
        });

        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                // Nothing will be happened when clicked on no button                // of Dialog            }
        });

        alertbox.show();
    }

    return super.onKeyDown(keyCode, event);
}