Android - Confirm app exit with toast

后端 未结 6 680
滥情空心
滥情空心 2020-12-08 23:33

I\'m new to Android development and I want it so when the user presses the back button on the main activity, a toast message appears with a \"confirm exit by pressing the ba

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 00:23

    Best and simple solution with Toast

    In Java

    private Toast exitToast;
    
    @Override
    public void onBackPressed() {
        if (exitToast == null || exitToast.getView() == null || exitToast.getView().getWindowToken() == null) {
            exitToast = Toast.makeText(this, "Press again to exit", Toast.LENGTH_LONG);
            exitToast.show();
        } else {
            exitToast.cancel();
            finish();
        }
    }
    

    In Kotlin

    private var exitToast: Toast? = null
    
    override fun onBackPressed() {
        if (exitToast == null || exitToast!!.view == null || exitToast!!.view.windowToken == null) {
            exitToast = Toast.makeText(this, "Press again to exit", Toast.LENGTH_LONG)
            exitToast!!.show()
        } else {
            exitToast!!.cancel()
            finish()
        }
    }
    

提交回复
热议问题