重置Android警报对话框中的复选框

时间:2011-03-18 05:42:28

标签: android android-widget

我正在使用带有setMultiChoiceItems的AlertDialog让用户选择多个工作正常的项目。问题是,下次出现AlertDialog时,它仍然会检查项目。我尝试通过覆盖onPrepareDialog来取消选中它们,但它无法正常工作。这是我的代码:

@Override
    protected Dialog onCreateDialog( int id ) 
    {
        String[] PROJECTION=new String[] { Contacts._ID,
                Contacts.DISPLAY_NAME,
                    Phone.NUMBER};

        String number = null;


        String[] ARGS={String.valueOf(Phone.TYPE_MOBILE)};

            c=managedQuery(Phone.CONTENT_URI,
            PROJECTION, Phone.TYPE+"=?",
                ARGS, Contacts.DISPLAY_NAME);

            while (c.moveToNext()) {
                number = c.getString(1);
                names.add(number);
                numbers.add(c.getString(2));
            }
            CharSequence[] cs = names.toArray(new CharSequence[names.size()]);
            selection = new boolean[names.size()];
             return new AlertDialog.Builder(this)

             .setTitle("Pick Contacts")
             .setMultiChoiceItems(cs,
                     selection, new DialogInterface.OnMultiChoiceClickListener(){
                         public void onClick(DialogInterface dialog, int whichButton,
                                 boolean isChecked) {
                             if(isChecked){
                                 names1.add(names.get(whichButton));
                                 numbers1.add(numbers.get(whichButton));
                                 isChecked = false;

                             }else{
                                 names1.remove(names.get(whichButton));
                                 numbers1.remove(numbers.get(whichButton));
                             }

                         }
                     })
                     .setPositiveButton( "OK", new DialogButtonClickHandler() )
                     .setNegativeButton( "Cancel", new DialogButtonClickHandler1() )
            .create();

    }

 @Override
 protected void onPrepareDialog(int id, Dialog dialog) {

     final AlertDialog alert = (AlertDialog)dialog;
     final ListView list = alert.getListView();

     for(int i = 0 ; i < list.getCount(); i++){
         list.setItemChecked(i, false);  
     }

 }

我尝试使用list.setItemsChecked(i,true)检查所有项目并且其工作但取消选中不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

要清除复选框,您只需通过布尔数组“选择”并将所有条目设置为false。

答案 1 :(得分:0)

我解决了这个问题,下面介绍的代码已经在我的应用“自动发送电子邮件”中应用了:

https://play.google.com/store/apps/details?id=com.alexpap.EmailPicturesFree

此应用会自动将您制作的每张图片发送到收件人电子邮件列表。以下功能用于选择收件人列表,这些收件人将接收您制作的图片。图片即时发送。 整个代码在EmailParametersActivity类中。适用于minSdkVersion =“5”。

//class variables

private EditText emailSendEdit;
private EditText passwordEdit;
private EditText passwordRepeatEdit;
private EditText emailReceiveEdit;
//array with all contacts used in multiselection dialog. Each entry is a string - name and email separated with new line (\n)
public static String[] contactArray;    
public static List<Integer> mSelectedItems = new ArrayList<Integer>(); //list of selected item IDs in multiselection dialog
//list of all contacts - name and email separated with new line (\n) for each entry (contact)   
public static List<String> contactList;

// onCreate()方法中的一些定义

    emailSendEdit = (EditText) findViewById(R.id.send_email);
    passwordEdit = (EditText) findViewById(R.id.password);
    passwordRepeatEdit = (EditText) findViewById(R.id.password_repeat);
    emailReceiveEdit = (EditText) findViewById(R.id.receive_email);

    emailReceiveEdit.setOnLongClickListener(new myLongListener());

// onCreate()方法结束

private class myLongListener implements View.OnLongClickListener {

    @SuppressWarnings("deprecation")
    @Override
    public boolean onLongClick(View v) {
        if (contactList == null || contactList.isEmpty()) {
         //populate contacts sorted ahphabetically
           contactList = populateContacts(EmailParametersActivity.this);
           contactArray = new String[contactList.size()];
           contactList.toArray(contactArray); 
         }
         showDialog (0);
         return false;
    }

}

    //We enter here only once, when the dialog is opened for the first time
    @Override
    protected Dialog onCreateDialog( int id ) 
    {
        mSelectedItems = new ArrayList();

        return  new AlertDialog.Builder( this )
            .setTitle( "Contacts" )
            .setMultiChoiceItems( contactArray, null, new DialogSelectionClickHandler() {
                   @Override
                   public void onClick(DialogInterface dialog, int which,
                           boolean isChecked) {
                       if (isChecked) {
                           // If the the item is checked, add its ID to the selected IDs
                           mSelectedItems.add(which);
                       } else if (mSelectedItems.contains(which)) {
                           // Else, if the ID of the item is already in the array, remove it 
                           mSelectedItems.remove(Integer.valueOf(which));
                       }
                   }
               }) 
            .setPositiveButton( "OK", new DialogButtonClickHandler() )
            .setNegativeButton("Cancel", new DialogButtonClickHandler() )
            .create();
    }

    //We enter here every time the dialog is opened
    @Override
     protected void onPrepareDialog(int id, Dialog dialog) {
        //clear all previously selected item IDs 
        mSelectedItems.clear();

        AlertDialog alert = (AlertDialog) dialog;

        //get List of dialog checked items
        ListView dialogListView = alert.getListView();

        //uncheck all previously checked items 
        for(int i = 0 ; i < dialogListView.getCount(); i++){
             dialogListView.setItemChecked(i, false);  
        }

     }
    //nothing to do here, we expect the result - list of checked items on click of OK button  
    public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
    {
        public void onClick( DialogInterface dialog, int clicked, boolean selected )
        {
            Log.i( "ME", contactArray[ clicked ] + " selected: " + selected );
        }
    }

    //Here we take the result - the list of checked items, from which we construct the string with selected emails
    //separated with coma
    public class DialogButtonClickHandler implements DialogInterface.OnClickListener
    {
        public void onClick( DialogInterface dialog, int clicked )
        {
            switch( clicked )
            {
                case DialogInterface.BUTTON_POSITIVE:
                    String receiveEmailList = getSelectedItems();
                    String strReceiveEmail = emailReceiveEdit.getText().toString();
                    if (strReceiveEmail != null && strReceiveEmail.length() > 0){
                        if (receiveEmailList.length() > 0){
                            strReceiveEmail = strReceiveEmail + "," + receiveEmailList;
                        }
                    } else {
                        strReceiveEmail = receiveEmailList;
                    }
                    emailReceiveEdit.setText(strReceiveEmail);

                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    dialog.dismiss();
                    break;

            }
        }
    }
    //we build the result. It is a string of selected items. Each item is a string with format - "name \n email". 
    //We take only the email in the result string; 
    protected String getSelectedItems(){

        String emailList = "";

        for( int i = 0; i < mSelectedItems.size(); i++ ){ //number of selected items in the dialog.

            int j = (int) mSelectedItems.get(i); // get the ID of current selected item. It is equal to j;

            Log.i( "ME", contactArray[ i ] + " selected: " +  contactArray[ j ]); 

            String [] nameEmail =  contactArray[ j ].split("\n");  //get email only
            emailList = emailList + nameEmail[1] + ","; // createte a string with selected emails, separated with coma.

        }
         //remove the last coma in the string
        if (emailList.length() > 1) {
            emailList = emailList.substring(0, emailList.length() - 1);
        }
        //if nothing selected return emty string.
        if (emailList.indexOf("@") < 1){ 
            emailList = "";
        }

        return emailList;
    }

最后,这个功能可以与名称和电子邮件进行协调

    @SuppressLint("InlinedApi")
    public List populateContacts(Context context) {

        ContentResolver cr = context.getContentResolver();

        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "phonetic_name");  // "display_name_source");

        List <String> contactList = new ArrayList <String> ();

        if (cur.getCount() > 0) {

            while (cur.moveToNext()) {

                //Get ID and Name form CONTACTS CONTRACTS
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                //While we have cursor get the email 
                Cursor emailCur = cr.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                + " = ?", new String[] { id }, null);
                while (emailCur.moveToNext()) {
                    // This would allow you get several email addresses
                    // if the email addresses were stored in an array
                    String email = emailCur
                            .getString(emailCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    contactList.add(name + "\n" + email);

                }
                emailCur.close();
            }

        }

        cur.close();
        //Sort contact list alphabetically - ascending (without fist item) 
        List<String> subList = contactList.subList(1, contactList.size());
        Collections.sort(subList);

        return contactList;

    }