How do I get the position selected in a RecyclerView?

前端 未结 13 2497
自闭症患者
自闭症患者 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 05:05

    A different method - using setTag() and getTag() methods of the View class.

    1. use setTag() in the onBindViewHolder method of your adapter

      @Override
      public void onBindViewHolder(myViewHolder viewHolder, int position) {
          viewHolder.mCardView.setTag(position);
      }
      

      where mCardView is defined in the myViewHolder class

      private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
                 public View mCardView;
      
                 public myViewHolder(View view) {
                     super(view);
                     mCardView = (CardView) view.findViewById(R.id.card_view);
      
                     mCardView.setOnClickListener(this);
                 }
             }
      
    2. use getTag() in your OnClickListener implementation

      @Override
      public void onClick(View view) {
          int position = (int) view.getTag();           
      
      //display toast with position of cardview in recyclerview list upon click
      Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
      }
      

    see https://stackoverflow.com/a/33027953/4658957 for more details

提交回复
热议问题