我不是很得意這個解決方案,由於循環,但這是短名單的選擇:
你可以從一個偵聽器,則viewHolder從視圖和適配器點擊查看從視圖中保持器位置,最後使用這些方法:
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;
}
一種簡單的方法來定義聽衆here。
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
使用this得到viewHolder:
@Override
public void onClick(View v) {
MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v);
holder.textView.setText("Clicked!");
}
檢查view type到know when點擊的觀點是父母還是孩子
//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;
}
使用 「點擊收聽」 你的視圖以及使用庫方法的視圖和適配器位置。如果它不是一個很長的列表,可以從第一個位置迭代到單擊的位置(parent?count = 0:count ++),count是循環後的子集。如果你檢查他們的代碼,你會發現他們做同樣的地方。 – albodelu