Why does OnClickListener on a ViewHolder don't work?

前端 未结 3 1519
孤街浪徒
孤街浪徒 2020-11-30 06:36

I\'m trying to implement a way to handle item selection on a RecyclerView. I personally don\'t like the way suggested in some answers on SO of passing through g

相关标签:
3条回答
  • 2020-11-30 07:04

    Simplely Click Handler your ViewHolder. Recycler View don't have special attaching click handlers like ListView which has the method setOnItemClickListener().

    ** public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener

    ** in public ViewHolder(Context context, View itemView) set public void onClick(View view)

    ** get position by: int position = getLayoutPosition(); User user = users.get(position);

    0 讨论(0)
  • 2020-11-30 07:11

    Looking at the updated code: you are not setting the onClickListener to any of the views in the ViewHolder. It is an understandable mistake to forget the click listener.

    Just use:

    tvName.setOnClickListener(this);
    star.setOnClickListener(this);
    

    You can set to both or just one of them. You can also simply get the parent layout of these two views, so that the whole item itself in the adapter can be clickable.

    itemView.setOnClickListener(this);
    
    0 讨论(0)
  • 2020-11-30 07:23

    You can do it in your onBindViewHolder

             @Override
            public void onBindViewHolder(ReportViewHolder holder, int position {
          holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override 
            public void onClick(View arg0) { 
            // handle your click here. 
        } }); 
    }
    
    0 讨论(0)
提交回复
热议问题