问题
While i was looking at some tutorials about recycler view.some of them used the viewHolder constructor to attach the onClick listener while some of them used the onBindViewHolder method. which method is the best place to attach the onclicklistener. i'm really confused
回答1:
The method onBindViewHolder
is called every time when you bind your view with data. So there is not the best place to set click listener. You don't have to set OnClickListener
many times for the one View
. So the best solution is to set click listener in onCreateViewHolder
method. But the important thing is a how do you implement on click listener. If you for example want to get some model from list you can use getAdapterPosition()
method from ViewHolder
.
Look at the exmaple
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.view_magazine_list_item, null);
final ViewHolder result = new ViewHolder(view);
view.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
YourObject yourobject = yourObjectsList.get(result.getAdapterPosition()));
}
});
return result;
}
回答2:
In ViewHolder
is the better place:
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//views declare here
public ItemViewHolder(View convertView)
{
super(convertView);
... ...
convertView.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
//do something to view here
//also you can get view position by 'getPosition()' here
}
}
回答3:
Best practice to use the onClickListener
inside the ViewHolder
class of the Recyclview
like below:-
public class ViewHolder extends RecyclerView.ViewHolder{
private View YOUR_VIEW;
public ViewHolder(@NonNull View itemView) {
super(itemView);
YOUR_VIEW = itemView.findViewById(R.id.YOUR_VIEW);
YOUR_VIEW.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext,"Position==>> "+getAdapterPosition(),Toast.LENGTH_LONG).show();
}
});
}
}
来源:https://stackoverflow.com/questions/28904479/best-place-to-attach-onclicklistener-in-recyclerview