Good practices indicate that it is better to do the assignment of ViewHolder
and with the function getAdapterPosition()
you can get the position by clicking on the element, so you can get the data with tu_lista[posición]
or tu_lista.getItem(posición)
class ViewHolder extends RecyclerView.ViewHolder {
Context mContext;
ImageView ivPhoto;
TextView tvTitle;
ViewHolder(View itemView) {
super(itemView);
mContext = view.getContext(); //obtener el context si se necesita más adelatne
ivPhoto = (ImageView) itemView.findViewById(R.id.iv_photo);
tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
ivPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "viewClick on " + mTitle.getText() + " position " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
//Aquí puedes recuperar datos tu_lista[getAdapterPosition()]
}
});
}
}
Compute the click
The parent container is itemView
In any element
The click listener must be assigned to the parent container itemView
if the parent container is a layout
as LinearLayout
, RelativeLayout
etc ..
the attribute android:clickable="true"
must be assigned so that it can receive the click.
For a simple click:
itemView.setOnClickListener(new View.OnClickListener()...
For a long press:
itemView.setOnLongClickListener(new View.OnLongClickListener()...
Each item separately
If in the view we want that if you click on the image you should compute something like the icon favorito
ivPhoto.setOnClickListener(new View.OnClickListener()...