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
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()
}
}