Single selection in RecyclerView

后端 未结 15 963
深忆病人
深忆病人 2020-11-22 15:15

I know there are no default selection methods in recyclerview class, But I have tried in following way,

public void onBindViewHolder(ViewHolder holder, final         


        
15条回答
  •  囚心锁ツ
    2020-11-22 16:11

    This is how its looks

    Inside your Adapter

    private int selectedPosition = -1;
    

    And onBindViewHolder

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    
        if (selectedPosition == position) {
            holder.itemView.setSelected(true); //using selector drawable
            holder.tvText.setTextColor(ContextCompat.getColor(holder.tvText.getContext(),R.color.white));
        } else {
            holder.itemView.setSelected(false);
            holder.tvText.setTextColor(ContextCompat.getColor(holder.tvText.getContext(),R.color.black));
        }
    
        holder.itemView.setOnClickListener(v -> {
            if (selectedPosition >= 0)
                notifyItemChanged(selectedPosition);
            selectedPosition = holder.getAdapterPosition();
            notifyItemChanged(selectedPosition);
        });
    }
    

    Thats it! As you can see i am just Notifying(updating) previous selected item and newly selected item

    My Drawable set it as a background for recyclerview child views

    
    
        
            
        
    
    

提交回复
热议问题