由于循环,我对这个解决方案不是很自豪,但这是短名单的替代方案:
你可以从监听器获取点击的视图,从视图获取viewHolder,从视图持有者获取适配器位置,最后使用这些方法:
使用此方法
/**
* 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);
}
另见
/**
* 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;
}
在这里定义侦听器的简单方法。
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
使用它来获取 viewHolder:
@Override
public void onClick(View v) {
MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v);
holder.textView.setText("Clicked!");
}
检查视图类型以了解单击的视图何时是父视图或子视图
//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;
}