1.Simple Click Handler within ViewHolder
RecyclerView
does not have special provisions for attaching click handlers to items unlike ListView
which has the method setOnItemClickListener()
. To achieve a similar effect, we can attach click events within the ViewHolder
within our adapter:
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
// ...
// Used to cache the views within the item layout for fast access
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvName;
public TextView tvHometown;
private Context context;
public ViewHolder(Context context, View itemView) {
super(itemView);
this.tvName = (TextView) itemView.findViewById(R.id.tvName);
this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
// Store the context
this.context = context;
// Attach a click listener to the entire row view
itemView.setOnClickListener(this);
}
// Handles the row being being clicked
@Override
public void onClick(View view) {
int position = getLayoutPosition(); // gets item position
User user = users.get(position);
// We can access the data within the views
Toast.makeText(context, tvName.getText(), Toast.LENGTH_SHORT).show();
}
}
// ...
}
Another way is my preferred way.. but this is also a fine way to go about it.
My onBindViewHolder
@Override
public void onBindViewHolder(CategoryViewHolder holder, int position) {
Category category = mCategories.get(position);
holder.tvTitle.setText(category.getTitle());
holder.tvDescription.setText(category.getDescription());
holder.rlContainer.setOnClickListener(mClickListener);
holder.rlContainer.setTag(holder);
}
My class level (Adapter object of View.OnClickListner)
View.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
CategoryViewHolder holder = (CategoryViewHolder) view.getTag();
int position = holder.getAdapterPosition();
startAppointmentBookingFor(mCategories.get(position));
}
};
so basically attach the listener to any view in your holder (I try to put it on container only), then extract it out on the onclick
and handle positions etc.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…