Skip to content
Advertisement

Allow user to select only 3 items in recyclerview

Basically I want user to select only 3 items from a list in recyclerview

My adapter class holder onclicklistener code:

holder.addproduct.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {


        ld.setSelected(!ld.isSelected());

        if (ld.isSelected()) {
            holder.addproduct.setImageDrawable(v.getResources().getDrawable(R.drawable.ic_checked));
        } else {
            holder.addproduct.setImageDrawable(v.getResources().getDrawable(R.drawable.ic_add_black_24dp));
        }

    }
});

My model class:

public class Product {
    private boolean isSelected = false;

    public Product() {

    }

    public Product(boolean isSelected) {
        this.isSelected = isSelected;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

isSelected is used to get value of selected items in fragment. Any help would be appreciated.

Advertisement

Answer

Make a global varaible i.e numOfSelectedItems

holder.addproduct.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        boolean newVal = !ld.isSelected();
        if(newVal && numOfSelectedItems >= 3) return;
        ld.setSelected(newVal);
  
        if (newVal)) {
           numOfSelectedItems++;
        } else {
            numOfSelectedItems--;
        }

    }
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement