Wednesday, July 6, 2011

Android - AlertDialog with buttons

In previous article AlertDialog, I explained how to build a simple alert dialogs in android. Here, we will see how to add buttons like yes,no or open,cancel or something of that sort.

Steps:
  • Create your dialog using AlertDialog.Builder
  • Use API methods like setPositiveButton or setNegativeButton or both to add buttons
  • Define handlers or event listeners to the buttons.
Sample code
public class MyActivity extends Activity {
private AlertDialog confirmBox = null;
/*
* Other parts of code,omitted.
*/
private void createDialog(){
confirmBox = new AlertDialog.Builder(MyActivity.this).setTitle("Confirm").setMessage("Are you sure you want to delete this entry?").
setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/**
* TO:DO add code to handle this action.
*/
MyActivity.this.confirmBox.dismiss();
}
}).setNegativeButton("No",null).show();
}
}
As you can see, setNegativeButton() and setPositiveButton() takes two arguments. The first argument is the label/caption for the button. In our case it is the yes and no . The second argument is the onclickhandler. You can also supply null if you want android to take default action applicable. In the above example, we have supplied a handler for positive button and null for negative button.


Result

No comments:

Post a Comment