Getting a Reference to ViewHolder on RecyclerView Click

后端 未结 4 2062

This is my first attempt at implementing the RecyclerView. I have implemented a Callback interface between the Adapter and the V

相关标签:
4条回答
  • 2020-12-05 10:49

    Actually you can do better than getTag by calling getChildViewHolder(View child) on the RecyclerView:

    @Override
    public void onClick(View v) {
        MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v);
        holder.textView.setText("Clicked!");
    }
    
    0 讨论(0)
  • 2020-12-05 10:53
    @Override
    public void onClick(View v) {
        int pos = getAdapterPosition(); //getPosition() is deprecated 
        notifyItemChanged(pos);
    }
    

    notifyItemChanged will notify your onBindViewHolder, then you can do something like this

    public void onBindViewHolder(RoomViewHolder roomViewHolder, int i) {
        Room r = getItem(i);
        roomViewHolder.label.setText(r.name);
        if(i == pos){ // Do Something }
    
    }
    

    Whenever you click the item, it will change pos' value and trigger the // Do Something

    0 讨论(0)
  • 2020-12-05 10:55

    Turn out that RecycleView saves the view position in the view layout params, so if you just want the view position from to get the right item from the list you can use this:

    RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) v.getLayoutParams();
    lp.getViewPosition();
    
    0 讨论(0)
  • 2020-12-05 11:03

    you can set a tag for the editBtn in onBindViewHolder:

        public RoomViewHolder(View itemView, IRoomViewClick listener) {
            ....
            editBtn =(Button) itemView.findViewById(R.id.editbtn);
            //add tag for this view
            editBtn.setTag(this);
            ....
       }
    

    and get it in onClick

        @Override
        public void onClick(View view) {
            //getTag
            RoomViewHolder holder = (RoomViewHolder )(view.getTag());
            int pos = getPosition();
            mListener.editname(pos);
        ...
        }
    
    0 讨论(0)
提交回复
热议问题