Prompt user when Back button is pressed

前端 未结 5 1005
孤街浪徒
孤街浪徒 2021-02-13 16:01

Which is the good place to ask user, whether (s)he wants to exit the app when (s)he clicked the back button? I considered the onPause and onStop, but t

5条回答
  •  灰色年华
    2021-02-13 16:03

    This is a rather old question but it ranks high on Google so I figured it could need an Update:

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Do you want to exit the app?");
    
        // if user presses "Exit", then he is allowed to exit from application
        builder.setPositiveButton("Exit", (dialog, which) -> finish());
    
        // if user selects "Stay", just cancel this dialog and continue with app
        builder.setNegativeButton("Stay", (dialog, which) -> dialog.cancel());
    
        builder.create().show();
    }
    

提交回复
热议问题