Dec 16, 2010

Alert Dialog

1. Adding buttons

private AlertDialog getAlertDialog(String title, String message) {
        
        // Adding buttons
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message)
               .setTitle(title)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       dialog.cancel();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       dialog.cancel();
                   }
               });
        return builder.create();
    }

2. Adding List

private AlertDialog getAlertDialog(String title, String message) {
        
        // Adding List
        final CharSequence[] items = {"Red", "Green", "Blue"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Pick a color");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
            }
        });
        return builder.create();
    }

3. Checkboxes and radio bottons (Single Choice)

private AlertDialog getAlertDialog(String title, String message) {
        
        // Checkboxes and radio bottons
        final CharSequence[] items = {"Red", "Green", "Blue"};
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
            }
        });    
        return builder.create();
    }

4. Checkboxes and radio bottons (Multi Choice)

private AlertDialog getAlertDialog(String title, String message) {
        
        // Checkboxes and radio bottons
        final CharSequence[] items = {"Red", "Green", "Blue"};
        boolean[] bool = new boolean[] { true, false, false}; 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Pick a color");
        builder.setMultiChoiceItems(items, bool, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                // Add action
            }
        });
        return builder.create();
    }

No comments: