I'm not very proud of this solution, due to the loop, but this is an alternative for short lists:
You can get the clicked view from a listener, the viewHolder from the view and the adapter position from the view holder, finally use these methods:
Use this method
/**
* Returns the adapter position of the Child associated with this ChildViewHolder
*
* @return The adapter position of the Child if it still exists in the adapter.
* RecyclerView.NO_POSITION if item has been removed from the adapter,
* RecyclerView.Adapter.notifyDataSetChanged() has been called after the last
* layout pass or the ViewHolder has already been recycled.
*/
@UiThread
public int getChildAdapterPosition() {
int flatPosition = getAdapterPosition();
if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) {
return RecyclerView.NO_POSITION;
}
return mExpandableAdapter.getChildPosition(flatPosition);
}
Also see
/**
* Given the index relative to the entire RecyclerView for a child item,
* returns the child position within the child list of the parent.
*/
@UiThread
int getChildPosition(int flatPosition) {
if (flatPosition == 0) {
return 0;
}
int childCount = 0;
for (int i = 0; i < flatPosition; i++) {
ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);
if (listItem.isParent()) {
childCount = 0;
} else {
childCount++;
}
}
return childCount;
}
An easy way to define the listener here.
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
Use this to get the viewHolder:
@Override
public void onClick(View v) {
MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v);
holder.textView.setText("Clicked!");
}
Check the view type to know when the clicked view is a parent or a child
//Returns the view type of the item at position for the purposes of view recycling.
@Override
public int getItemViewType(int position) {
if (items.get(position) instanceof User) {
return USER;
} else if (items.get(position) instanceof String) {
return IMAGE;
}
return -1;
}