Here is the code for Adapter. Cards change color on selection. I want the user to select <= 5 cards only. How can I restrict? The user should not be allowed to select more than 5 cards.
@Override
public void onBindViewHolder(final OptionsViewHolder holder, int position) {
final OptionModel option=Options.get(position);
holder.OptionName.setText(option.getName());
holder.iv_card.setColorFilter(option.isSelected()? holder.item_view.getResources().getColor(R.color.Yellow) : holder.item_view.getResources().getColor(R.color.Dark_Blue));
if(!Disabled){
holder.iv_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
option.setSelected(!option.isSelected());
holder.iv_card.setColorFilter(option.isSelected() ? view.getResources().getColor(R.color.Yellow) : view.getResources().getColor(R.color.Dark_Blue));
}
});
}else {
holder.iv_card.setOnClickListener(null);
}
}
CodePudding user response:
Based your question try to make some changes, like declare an global variable in adapter and then use that variable.
int selectedCards=0;
@Override
public void onBindViewHolder(final OptionsViewHolder holder, int position) {
final OptionModel option=Options.get(position);
holder.OptionName.setText(option.getName());
holder.iv_card.setColorFilter(option.isSelected()? holder.item_view.getResources().getColor(R.color.Yellow) : holder.item_view.getResources().getColor(R.color.Dark_Blue));
if(!Disabled){
holder.iv_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(selectedCards<=5) {
selectedCards ;
option.setSelected(!option.isSelected());
holder.iv_card.setColorFilter(option.isSelected() ? view.getResources().getColor(R.color.Yellow) : view.getResources().getColor(R.color.Dark_Blue));
}
}
});
}else {
holder.iv_card.setOnClickListener(null);
}
if you are de-selecting any card then on de-select make sure you are decreasing the global variable's value as
selectedCards--;
if your query is resolved then mark as correct answer else still there is any question then write here .