Listener for BACK-button
Andrew Mclaughlin
How I can get any action for back-button when the alert dialog is shown? I have to ask user "Do you really want discard changes?"
At this time there is alert dialog for input on the screen.
12 Answers
Your initial question was not very clear on what you wanted to do. So if you want to show a dialog when a user presses the back button after having types something in the EditText- then you need to @Override the onBackPressed method in your Activity class.
@Override
public void onBackPressed() { // Here you want to show the user a dialog box new AlertDialog.Builder(context) .setTitle("Exiting the App") .setMessage("Are you sure?") .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // The user wants to leave - so dismiss the dialog and exit finish(); dialog.dismiss(); } }).setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // The user is not sure, so you can exit or just stay dialog.dismiss(); } }).show();
}You can look at the accepted answer here.
But if you only wanted to handle the back-button press on the Dialog itself, then there's already an answer for this question - basically you set an OnKeyListener on the dialog like this:
dialog.setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface arg0, int keyCode,KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { /* The user pressed back button - do whatever here. Normally you dismiss the dialog like dialog.dismiss(); */ } return true; } });Look at the accepted answer here.
10builder.setNegativeButton(R.string.btn_rev, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { //если что-то ввели и нажали Назад if (edText.getText() != null) { // onBackPressed(); //here's code for back-button } } }); 1