Pages

Tuesday, March 25, 2014

How to enable/disable buttons of the AlertDialog in Android?

Hello friends,
Today m posting to how enable/disable AlertDialog positive and negative Buttons.


AlertDialog.Builder builder = new AlertDialog.Builder(AddSchedule.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Alert dialog title");
builder.setMessage("Dialog message");
builder.setPositiveButton("Button1", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
        //DO TASK
    }
});
builder.setNegativeButton("Button2", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
        //DO TASK
    }
});

AlertDialog dialog = builder.create();
dialog.show();

//After calling show method, you need to check your condition and 
//enable/ disable buttons of dialog 
if(your_condition_true)
    dialog.getButton(AlertDialog.BUTTON1).setEnabled(false); //BUTTON1 is positive button

For nagative button

dialog.getButton(AlertDialog.BUTTON2).setEnabled(false); //BUTTON2 is negative button

And the setOnShowListener since level 8 API (FroYo), does the same,


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new OnShowListener() 
{
    @Override
    public void onShow(DialogInterface dialog) 
 {
        if(condition)
        ((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
});
dialog.show();


No comments:

Post a Comment