This example shows how to create an Alert Dialog box also known as a message box.
Main Steps
1. Create an activity that implements the OnClickListener interface.
2. Add a button to launch the alert dialog box.
3. In the activity's public void onClick(View v) method create an AlertDialog.Builder object.
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
4, Set the alert's title, message, and optionally an icon.
5. Set the positive and negative buttons and provide them onClick listeners. The listeners each get passed an anonymous class that implements the interface: DialogInterface.OnClickListener.
The official documentation on the DialogInterface.OnClickListener interface.
http://developer.android.com/reference/android/content/DialogInterface.OnClickListener.html
DialogInterface.OnClickListener
"Interface used to allow the creator of a dialog to run some code when an item on the dialog is clicked."
public abstract void onClick (DialogInterface dialog, int which)
"This method will be invoked when a button in the dialog is clicked."
Parameters
dialog The dialog that received the click.
which The button that was clicked or the position of the item clicked.
This is an example of code that creates a two-button dialog box:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_Alert;
btn_Alert = (Button) findViewById(R.id.btn_Alert);
btn_Alert.setOnClickListener(this);
}
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Confirm Delete...");
alert.setMessage("Are you sure you want delete this file?");
alert.setIcon(R.drawable.reindeer);
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked YES",
Toast.LENGTH_LONG).show();
// dialog.cancel() method is not needed for either the Yes or No buttons because each closes the alert dialog box without it.
// This example detects the button clicked and does not rely on the 'which' argument.
dialog.cancel();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked NO",
Toast.LENGTH_LONG).show();
dialog.cancel(); // Optional
}
});
alert.show();
};
}