我已经创建了RecyclerViewList,但是我需要为列表设置一个限制!我需要将其限制为最多3个选择。
我的列表
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
List<String> itemTitles;
SparseBooleanArray sparseBooleanArray; // for identifying: in list which items are selected
OnRecyclerViewItemClickListener listener;
int selectedItemCount;
private int lastSelectedPosition = -1;
public RecyclerViewAdapter(List<String> itemTitles, OnRecyclerViewItemClickListener listener)
{
this.itemTitles = itemTitles;
sparseBooleanArray = new SparseBooleanArray();
this.listener = listener;
selectedItemCount = 0;
}
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,parent,false);
return new RecyclerViewAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position) {
holder.itemTextView.setText(itemTitles.get(position));
if (sparseBooleanArray.get(position))
{
holder.itemTextView.setBackgroundColor(Color.TRANSPARENT);
holder.itemTextView.setTextColor(Color.rgb(114, 47, 55));
}
else
{
holder.itemTextView.setBackgroundColor(Color.TRANSPARENT);
holder.itemTextView.setTextColor(Color.rgb(100, 100, 100));
}
}
@Override
public int getItemCount() {
return itemTitles.size();
}
/******** View Holder Class*/
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView itemTextView;
public TextView alert;
public ViewHolder(View itemView) {
super(itemView);
itemTextView = itemView.findViewById(R.id.itemTextView);
itemTextView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (!sparseBooleanArray.get(getAdapterPosition()))
{
if (selectedItemCount > 3) {
sparseBooleanArray.put(getAdapterPosition(),true);
}
listener.selectedItemCount(selectedItemCount); // calling the method in main activity Because: in our case mainActivity our created interface for clicklisteners
notifyItemChanged(getAdapterPosition());
}
else // if clicked item is already selected
{
if (selectedItemCount < 3) {
sparseBooleanArray.put(getAdapterPosition(),true);
}
sparseBooleanArray.put(getAdapterPosition(),false);
listener.selectedItemCount(selectedItemCount); // calling the method in main activity Because: in our case mainActivity our created interface for clicklisteners
notifyItemChanged(getAdapterPosition());
}
}
}
public interface OnRecyclerViewItemClickListener{
public void selectedItemCount(int count);
}
}