How to check exit confirmation on clicking back button in Android App?
HTML-код
- Опубликовано: 11 сен 2024
- In this video it shows the code to check exit confirmation on clicking back button in Android App. Basically, for this implementation it follows below two steps:
1. Override OnBackPressedCallback method.
2. Create and Show AlertDialog
I hope you like this video. For any questions, suggestions or appreciation please contact us at: programmerworl... or email at: programmerworld1990@gmail.com
Complete source code and other details/ steps of this video are posted in the below link:
programmerworl...
However, the main Java code is copied below also for reference:
package com.programmerworld.exitconfirmationonbackbuttonpress;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) - {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setMessage("Do you want to exit?");
alertDialogBuilder.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAndRemoveTask();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
return insets;
});
}
}
--