I've implemented Recyclerview onclickListener from this Stack overflow solution. This solution works fine for the recycler item clicks. But I can't able to get which subview(ex: ImageView,Button) is clicked from the row.
mAttachmentRecyclerview.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (view.getId()==R.id.attachmnet_remove) {
attachmentsList.remove(position);
mAttachmentAdapter.notifyDataSetChanged();
attachmentCount--;
}
}
}
));
onItemClick(view,position)
always returns view id as -1
How do I track whick view is clicked??
Below is a ViewHolder
that contains two text views viz. title
and description
:
public class CustomViewHolder extends RecyclerView.ViewHolder {
private final OnViewClickListener mListener;
public final TextView title;
public final TextView description;
public interface OnViewClickListener {
void onViewClick(View v, int adapterPosition);
}
public CustomViewHolder(View itemView, OnViewClickListener mListener) {
super(itemView);
this.mListener = mListener;
title = (TextView) itemView.findViewById(R.id.titleTextView);
description = (TextView) itemView.findViewById(R.id.descriptionTextView);
title.setOnClickListener(onClickListener);
description.setOnClickListener(onClickListener);
}
private final View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
mListener.onViewClick(view, getAdapterPosition());
}
};
}
Both of these subviews have an OnClickListener
attached to them that calls the custom OnViewClickListener
implementation passing the View
that was clicked as well as the position of the RecyclerView
item in the adapter that received the click event.
Finally use View.getId()
to retrieve the clicked view's id in OnViewClickListener
implementation.
That answer is outdated in that it uses RecyclerView.getChildPosition(View)
which is deprecated. Try replacing it with RecyclerView.getChildAdapterPosition(View)
.
If I was you, I would just create listeners for every ViewHolder
and its child views that you want to listen to. Honestly, I don't seem to see the benefit of using that more complicated method that you referenced. Also, that method will only tell you that an item was clicked, nothing about the item's child views.
In addition, according to the docs, RecyclerView.OnItemTouchListener
is meant to be used when you want to detect a touch to an item while the list is scrolling, not for regular or direct touches.
Set Tags
You can set Tag to your views while initializing them via:
view1.setTag(1);
This will set the view Tag to 1.
then In onItemClick method:
@Override
public void onItemClick(View view, int position) {
if(view.getTag()==1)
{
//do something
}
else
{
//do something else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With