Question

I want to ask how to set the state of some items in Dialog check box to be pre-checked. I have to following code:

String[] typeOfTransport;

    typeOfTransport = new String[modes.length];

    final boolean[] itemsChecked = new boolean[modes.length];
    for (int i = 0; i < modes.length; i++) 
    {       
        typeOfTransport[i] = modes[i].Name;                     
    }

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle("Select your transport:");
    dialogBuilder.setMultiChoiceItems(typeOfTransport, itemsChecked, new DialogInterface.OnMultiChoiceClickListener()
    {           
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) 
        {               
            itemsChecked[which] = isChecked = true;              
        }           
    });

    dialogBuilder.setPositiveButton("Set", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) 
        {
            String selectetdVal = " ";
            for (int i = 0; i < modes[0].Name.length(); i++) 
            {  
               if (itemsChecked[i]) 
               {  
                 selectetdVal = selectetdVal + modes[i].Name+ " ";
                 itemsChecked[i]=false;                  
               }
            }               
            Toast.makeText(MainWindow.this, selectetdVal,Toast.LENGTH_SHORT).show();
        }

    });     

    AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();
    return true;
}

And I get the dialog correctly everything is set and ready to be checked by the user but I want on some of the items in the dialog to be pre-checked when the user calls the dialog for the first time.

Was it helpful?

Solution

hat's what the second argument on setMultiChoiceItems do, but you are basically passing an array of boolean values recently created (they are all false).

Try setting the positions you want pre-checked as true before calling setMultiChoiceItems.

You can reuse the for loop you already have to do something like this:

final boolean[] itemsChecked = new boolean[modes.length];
for (int i = 0; i < modes.length; i++) 
{       
    typeOfTransport[i] = modes[i].Name;  

    itemsChecked[i] = modes[i].Selected;                 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top