How do I get the position selected in a RecyclerView?

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

    I think the most correct way to get item position is

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override public void onClick(View v) {
          View view = v;
          View parent = (View) v.getParent();
          while (!(parent instanceof RecyclerView)){
            view=parent;
            parent = (View) parent.getParent();
          }
          int position = recyclerView.getChildAdapterPosition(view);
    }
    

    Because view, you click not always the root view of your row layout. If view is not a root one (e.g buttons), you will get Class cast exception. Thus at first we need to find the view, which is the a dirrect child of you reciclerview. Then, find position using recyclerView.getChildAdapterPosition(view);

提交回复
热议问题