Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic alertdialog with radio buttons

Tags:

android

I am trying to make the item list dynamic, so i can add to it on runtime, but i have no idea. CharSeqence isnt dynamic, and no clue how to use the adapter option, how could i change my code to be dynamic?

private void alertDialogLoadFile() {

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Choose:");  
    CharSequence[] items = { "moshe", "yosi", "ee" };
    alert.setSingleChoiceItems(m_items , -1, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int item){
            /* User clicked on a radio button do some stuff */
        }
    });

    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int id) {
    }
    });

    alert.setNegativeButton("No", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });


    AlertDialog ad = alert.create();
    ad.show();

}
like image 451
rayman Avatar asked Jan 29 '10 18:01

rayman


People also ask

How many buttons can be set up on an AlertDialog?

Dialog Design AlertDialog. A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout.

How to add radio button in alert dialog in Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view.

What is the difference between dialog and AlertDialog?

AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .


1 Answers

If you create the dialog in onCreateDialog(), you can implement onPrepareDialog() to change the choices before it's displayed to the user. For example:

protected void onPrepareDialog(int id, Dialog dialog) {    
    if (id == YOUR_DIALOG_ID) {

        // Create new adapter
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>();
        adapter.add("new items ...");
        ...

        // Use the new adapter
        AlertDialog alert = (AlertDialog) dialog;
        alert.getListView().setAdapter(adapter);
    }
}

You could also get the same effect by getting the adapter from the dialog (and casting it to the correct type) and adding or removing the items as you see fit. I'd probably lean towards simply creating a new adapter, because you won't have to worry about casting the value from getListAdapter() to the wrong type. However, reusing the adapter is probably a bit more memory efficient.

like image 97
Erich Douglass Avatar answered Sep 20 '22 23:09

Erich Douglass