How to check exit confirmation on clicking back button in Android App?

Veröffentlicht am: 24 April 2024
auf dem Kanal: Programmer World
225
5

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: https://programmerworld.co/contact/ or email at: [email protected]

Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/ho...


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


--


Auf dieser Seite können Sie das Online-Video How to check exit confirmation on clicking back button in Android App? mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Programmer World 24 April 2024 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 225 Mal angesehen und es wurde von 5 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!