By Alvin Alexander. Last updated: July 17, 2016
Here’s a source code snippet that shows how to create an Android AlertDialog
. If I remember right, I got the initial code from Stack Overflow, and then adapted it for my need, which was to confirm that the user wanted to delete an image from an image gallery:
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int choice) { switch (choice) { case DialogInterface.BUTTON_POSITIVE: try { String rootDir = FileUtils.getImagesDir(getActivity()); boolean fileWasDeleted = FileUtils.deleteFile(rootDir + "/" + imageFilename); if (fileWasDeleted) { Toast.makeText(getActivity(), "The file was deleted", Toast.LENGTH_SHORT).show(); } } catch (IOException ioe) { // TODO let the user know the file couldn't be deleted } break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("Delete this image?") .setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show();
If you understand Android programming this code should be pretty straightforward, so I won’t explain it here, other than to say that it looks like typical Java/Android “listener” style programming.