This will probably be one of the Android code snippets that I will need to go back to from time to time.
I’m sharing the codes we need to show an Android confirm dialog to prompt the user to click “yes” or “no”, or in my case, “OK” or “Cancel”.
The following code for Android confirm dialog is in my MainActivity.java
file:
Code snippet for “Android confirm dialog”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/** * MainActivity.java */ // package name import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); confirmDialog(); } private void confirmDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Record will be deleted and cannot be undone.") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Log.d("Dialog, clicked", "OK"); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Log.d("Dialog, clicked", "Cancel"); dialog.cancel(); } }) .show(); } } |
Run this on your Android phone or emulator. When you click OK or Cancel, you’ll see logs on Android Studio’s logcat “OK” or “Cancel”, whichever button you click.
The above code was adapted from (Android) Simple confirm dialog at Jymden.com, and then modified to work on my MainActivity.java.
By the way, I use Android Studio version 1.4 on Windows 7.