如何在我的recyclerView中选中所有复选框?

时间:2018-01-22 21:57:02

标签: java android android-recyclerview recycler-adapter

我的代码的结果是只检查了所有复选框 后滚过recyclerView中的复选框 - 当我向上滚动时,会检查它们。

单击按钮后如何检查它们?

在我的活动中,我有:

    private void publicButton() {

        publicContacts.setOnClickListener(new View.OnClickListener() {

 @Override
        public void onClick(View v) {

            //loop through the contacts
            int count = PopulistoContactsAdapter.theContactsList.size();

            for (int i = 0; i < count; i++) {
                PopulistoContactsAdapter.theContactsList.get(i).setSelected(true);
                }
        }
    });
}

对于recyclerViewAdapter

@Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
        //bind the views into the ViewHolder
        //selectPhoneContact is an instance of the SelectPhoneContact class.
        //We will assign each row of the recyclerview to contain details of selectPhoneContact:

        //The number of rows will match the number of phone contacts
        final SelectPhoneContact selectPhoneContact = theContactsList.get(position);

        //if the row is a matching contact
        if (viewHolder.getItemViewType() == 1)

        {
            //in the title textbox in the row, put the corresponding name etc...
            ((MatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
            ((MatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
            //((MatchingContact) viewHolder).check.setText("Cheeckbox" + position);
            ((MatchingContact) viewHolder).check.setChecked(theContactsList.get(position).isSelected);
            ((MatchingContact) viewHolder).check.setTag(position);

            ((MatchingContact) viewHolder).check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //pos is the row number that the clicked checkbox exists in
                    Integer pos = (Integer) ((MatchingContact) viewHolder).check.getTag();

                    Toast.makeText(context_type, theContactsList.get(pos).getPhone() + " clicked!", Toast.LENGTH_SHORT).show();

                    if (theContactsList.get(pos).getSelected()) {
                        theContactsList.get(pos).setSelected(false);
                    } else {
                        theContactsList.get(pos).setSelected(true);
                    }
                }
            });

            }
    }

onClick中的Adapter按计划为各个复选框工作;他们的国家得以保留。只是当我尝试使用活动中的按钮选择所有这些问题时才出现问题。

1 个答案:

答案 0 :(得分:1)

到目前为止,最简单的答案是,在完成所有notifyDataSetChanged()来电后,只需在适配器上拨打setSelected()即可。

从您的代码中,我无法判断PopulistoContactsAdapter是否是适配器实例,或者PopulistoContactsAdapter.theContactsList是否为静态变量...您需要一个适配器实例来调用{{1} }。如果您只引用notifyDataSetChanged(),则可以致电RecyclerView