Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all items which listed in recyclerview?

I have list of items inside of recyclerview, and they are multiple selectable.

I want to have select button to select all, and if selected deselect all. I didn't see any option to iterate through RecyclerView.Adapter to do that. How can I implement that?

Thank you.

like image 927
Mohamed Avatar asked Aug 08 '17 22:08

Mohamed


2 Answers

Try to maintain Selected item list and list of items in Adapter,

When you select "Select All" button, just add all item in selected item list and call notifyDataSetChanged

Just a sudo code

class adapter {
    ArrayList<Item> selected = new ArrayList<Item>();
    ArrayList<Item> items = new ArrayList<Item>();

    public void selecteAll() {
        selected.clear();
        selected.addAll(items);
        notifyDataSetChanged();
    }

    public void clearAll() {
        selected.clear();
        notifyDataSetChanged();
    }

    public void bindView() {
        Item item = items.get(position);

        if(selected.contains(item) {
            // Do selected action
        } else {
           // Non selecetd ctions
        }
    }

}
like image 154
Muthukrishnan Rajendran Avatar answered Sep 30 '22 20:09

Muthukrishnan Rajendran


In my case,

Step - 1 :- first globally initialize flag in activity class

boolean flagSelectAll = false;

Step - 2 :- Then set below code in Onclick of Button

@OnClick(R.id.btnSelectAll)
public void setBtnSelectAll(View view){
    for (int i=0;i<dMyItemLists.size();i++){
        if (dMyItemLists.get(i).isSelected()){
            flagSelectAll = true;
            dMyItemListAdapter.selectAllItem(false);
            dMyItemListAdapter.notifyDataSetChanged();
        }
        else {
            dMyItemListAdapter.selectAllItem(true);
            dMyItemListAdapter.notifyDataSetChanged();
        }
        break;
    }
}

Step - 3 :- Then create method selectAllItem in recyclerview's adpater class like below :

public void selectAllItem(boolean isSelectedAll) {
        try {
            if (itemList != null) {
                for (int index = 0; index < itemList.size(); index++) {
                    itemList.get(index).setSelected(isSelectedAll);
                }
            }
            notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
like image 35
khushbu vadi Avatar answered Sep 30 '22 21:09

khushbu vadi