How do I get the position selected in a RecyclerView?

前端 未结 13 2465
自闭症患者
自闭症患者 2020-11-27 04:40

I am experimenting with the support library\'s recyclerview and cards. I have a recyclerview of cards. Each card has an \'x\' icon at the top right corner to remove it:

13条回答
  •  醉梦人生
    2020-11-27 04:56

    onBindViewHolder() is called for each and every item and setting the click listener inside onBindVieHolder() is an unnecessary option to repeat when you can call it once in your ViewHolder constructor.

    public class MyViewHolder extends RecyclerView.ViewHolder 
          implements View.OnClickListener{
       public final TextView textView; 
    
       public MyViewHolder(View view){
          textView = (TextView) view.findViewById(R.id.text_view);
          view.setOnClickListener(this);
          // getAdapterPosition() retrieves the position here.
       } 
    
       @Override
       public void onClick(View v){
          // Clicked on item 
          Toast.makeText(mContext, "Clicked on position: " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
       }
    }
    

提交回复
热议问题