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.