Je ne suis pas très fier de cette solution, en raison de la boucle, mais cela est une alternative pour les courtes listes:
Vous pouvez obtenir la vue cliqué d'un auditeur, le viewHolder de la vue et l'adaptateur la position du support de vue, enfin utiliser ces méthodes:
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;
}
Un moyen facile de définir l'écouteur here.
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
Utilisez this pour obtenir le viewHolder:
@Override
public void onClick(View v) {
MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v);
holder.textView.setText("Clicked!");
}
Vérifiez la view type-know when la vue cliqué est un parent ou d'un enfant
//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;
}
l'aide d'un « clic d'écoute » vous obtenez la vue, et le titulaire de l'avis et la position de l'adaptateur en utilisant des méthodes de bibliothèque. Si ce n'est pas une liste très longue, vous pouvez itérer de la première position à la position cliquée (parent? Count = 0: count ++), count est votre childpostion après la boucle. Si vous vérifiez leur code, vous trouverez un endroit où ils font la même chose. – albodelu