取消选择所有列表视图复选框

Unselect all listview checkboxes

我有一个自定义列表视图,用于显示联系人的姓名和手机号码。列表视图在行布局中有复选框以及 "Select All" header 复选框。当我 select header 复选框时,所有列表视图复选框都被选中(除了那些在它们的数字之前没有 + 符号的)。现在的问题是当我取消select header 复选框时我无法取消选中它们。

public class MainActivity extends AppCompatActivity  {

    ListView list;
    Button btnDone;
    CustomAdapter adapter;
    CheckBox selectAll;
    ArrayList<Contacts> arrayList = new ArrayList<>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list = (ListView) findViewById(R.id.lst_contacts_chooser);
        btnDone = (Button) findViewById(R.id.btn_done);
        selectAll = (CheckBox)findViewById(R.id.selectAll);

        fetchContacts();

        adapter = new CustomAdapter(MainActivity.this,R.layout.contact_item,arrayList, selectAll);

        list.setAdapter(adapter);

    }

    private void fetchContacts(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ){
            askForPermission(android.Manifest.permission.READ_CONTACTS,1100);
        }else{
            new LoadContactsAyscn().execute();
        }
    }

    private void askForPermission(String permission, Integer requestCode) {
        System.out.println("sammy_reached_askForPermission");
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {

            if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
                // if (shouldShowRequestPermissionRationale(permission)) {  // for fragment

                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
                // requestPermissions(new String[]{permission}, requestCode);  // for fragment

            } else {

                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
                // requestPermissions(new String[]{permission}, requestCode); // for fragment
            }
        } else {
            new LoadContactsAyscn().execute();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        System.out.println("sammy_reached_onRequestPermissionsResult");
        if(ActivityCompat.checkSelfPermission(MainActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED){
            if(requestCode==1100){
                new LoadContactsAyscn().execute();
            }
            Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
        }
    }

    private class LoadContactsAyscn extends AsyncTask<Void, Void, ArrayList<Contacts>> {

        @Override
        protected ArrayList<Contacts> doInBackground(Void... params) {
            System.out.println("sammy_reached_LoadContactsAyscn");
            String name;
            String phone = null;
            String emailContact = null;

            if (arrayList != null) arrayList.clear();

            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    Contacts model = new Contacts();
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        System.out.println("Contact Name: " + name);
                        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                        while (pCur.moveToNext()) {

                            phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            System.out.println("Contact Phone: " + phone);

                        }
                        pCur.close();
                        Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
                        while (emailCur.moveToNext()) {
                            emailContact = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                            System.out.println("Contact Email: " + emailContact);
                        }
                        emailCur.close();
                    }
                    model.setName(name);
                    model.setMobile(phone);
                    model.setEmail(emailContact);
                    if(phone.contains("+"))
                        model.setPlus(true);
                    else
                        model.setPlus(false);
                    arrayList.add(model);

                }
            }



            return arrayList;
        }

        @Override
        protected void onPostExecute(ArrayList<Contacts> contacts) {
            // super.onPreExecute(contacts);
            adapter.notifyDataSetChanged();
        }
    }





}



public class CustomAdapter extends ArrayAdapter<Contacts> {

    private Context mContext;
    int resource;
    private CheckBox selectAll;
    private ArrayList<Contacts> arrayList = new ArrayList<Contacts>();

    public CustomAdapter(Context mContext, int resource, ArrayList<Contacts> arrayList, CheckBox selectAll) {
        super(mContext, resource, arrayList);
        this.resource = resource;
        this.mContext = mContext;
        this.arrayList = arrayList;
        this.selectAll = selectAll;
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        View v = convertView;
        final ViewHolder holder;
        if (v == null) {
            holder = new ViewHolder();

            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

            v = inflater.inflate(resource, parent, false);

            holder.tvName  = (TextView)v.findViewById(R.id.tvName);
            holder.tvMobEmail = (TextView)v.findViewById(R.id.tvMobEmail);
            holder.chkbox = (CheckBox)v.findViewById(R.id.chkbox);

            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        final Contacts item = arrayList.get(position);

        holder.tvName.setText(item.getName());
        if(TextUtils.isEmpty(item.getMobile()))
            holder.tvMobEmail.setText(item.getEmail());
        else
            holder.tvMobEmail.setText(item.getMobile());


        holder.chkbox.setChecked(item.isChecked());
        holder.chkbox.setTag(position);
        /*holder.chkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                   //item.setChecked(true);
                    holder.chkbox.setChecked(true);
                }else{
                    //item.setChecked(false);
                    holder.chkbox.setChecked(false);
                }

                notifyDataSetChanged();
            }
        });*/

        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                System.out.println("sammy_SelectAllBox "+isChecked);
                System.out.println("Total Size: "+getCount());
                System.out.println("Checked Size: "+getCheckedCount());
                if(isChecked){
                    for(int i=0;i<arrayList.size();i++){
                        if(arrayList.get(i).isPlus())
                            arrayList.get(i).setChecked(true);
                        else
                            arrayList.get(i).setChecked(false);
                    }
                    selectAll.setText("Unselect All");
                }else{

                        System.out.println("Total Size: "+arrayList.size());
                        System.out.println("Checked Size: "+getCheckedCount());
                        for(int i=0;i<arrayList.size();i++){
                            //if(arrayList.get(i).isPlus())
                            arrayList.get(i).setChecked(false);
                        }


                    selectAll.setText("Select All");
                }
                notifyDataSetChanged();

            }
        });


        return v;
    }

    class ViewHolder {

        TextView tvName, tvMobEmail;
        CheckBox chkbox;
    }

    private int getCheckedCount(){
        int count=0;
        for(int i=0;i<arrayList.size();i++){
            if (arrayList.get(i).isChecked()){
                count++;
            }
        }

        return count;

    }
}

更改了您的 setOnCheckedChangeListener

        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                System.out.println("sammy_SelectAllBox "+isChecked);
                System.out.println("Total Size: "+getCount());
                System.out.println("Checked Size: "+getCheckedCount());
                if(isChecked){
                    for(int i=0;i<arrayList.size();i++){
                        arrayList.get(i).setChecked(false);
                    }
                    selectAll.setText("Unselect All");
                }else{
                    for(int i=0;i<arrayList.size();i++){
                      arrayList.get(i).setChecked(true);
                    }
                    selectAll.setText("Select All");
                }
                notifyDataSetChanged();

            }
        });

你应该这样改。

holder.chkbox.setChecked(item.isChecked());

if(item.isChecked())
    holder.chkbox.setChecked(item.isChecked());
else
    holder.chkbox.setEnabled(false);

在适配器中 class。

You have to try selectAll check box in main activity. And its listener too. because selectAll doesn't need in adapter class. And in activity after select all listener use the adapter because modified data should be go to adapter

编辑

如果您想在任何项目未选中时取消选择,请使用

在 getView()

if(item.isChecked()) {
            holder.chkbox.setEnabled(true);
            holder.chkbox.setChecked(item.isChecked());
            notifyDataSetChanged();
        }else{

            if(item.isPlus()){
                holder.chkbox.setEnabled(true);
                holder.chkbox.setChecked(item.isChecked());

            }else{

                holder.chkbox.setChecked(false);
            }
            notifyDataSetChanged();

        }
     holder.chkbox.setTag(position);


holder.chkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                if(!item.isPlus()){
                    if(!selectAll.isChecked()){
                        holder.chkbox.setChecked(false);
                        Toast.makeText(mContext, "Please add +", Toast.LENGTH_SHORT).show();
                    }else{
                        holder.chkbox.setChecked(false);
                        Toast.makeText(mContext, "Please add + before", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        }
    });

根据sammy的帮助和建议