Issue
I have a RecyclerView and a like button inside of it. For example I want to make a Toast message when I clicked the button. Sample code:
class ViewHolder extends RecyclerView.ViewHolder{
Button button;
public ViewHolder(@NonNull View itemView) {
super(itemView);
button = itemView.findViewById(R.id.button);
}
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, ""+list.get(position).getId(), Toast.LENGTH_SHORT).show();
}
});
}
So is this way correct ? I'm not sure this must be inside of onBindViewHolder() because of performance issue? So can you tell me is there a better way for child item click event in RecyclerView? By the way these are only example codes. In real I'm dealing more complex things when I clicked the button(request to server).
Solution
You can simply do like this:
class ViewHolder extends RecyclerView.ViewHolder{
Button button;
public ViewHolderMultiple(@NonNull View itemView) {
super(itemView);
button = itemView.findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Toast.makeText(context, ""+list.get(getAdapterPosition()).getId(), Toast.LENGTH_SHORT).show();
}
}
Answered By - Kasım Özdemir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.