我通过getItemViewType设置不同的视图。
@Override
public int getItemViewType(int position) {
if (totalCartSize > productServiceSize) {
if (position < productServiceSize) {
return PRODUCT_SERVICE_TYPE;
} else if (position >= productServiceSize && position < totalCartSize) {
return PROJECT_TYPE;
}
} else {
return PRODUCT_SERVICE_TYPE;
}
return super.getItemViewType(position);
}
在点击行上我有callBackListener通过再次点击服务进行刷新,但在callBack中由于onBindViewholder错误的位置,我得到了错误的值。
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ProductServiceViewHolder) {
setProductServiceView((ProductServiceViewHolder) holder, holder.getAdapterPosition());
} else if (holder instanceof ProjectViewHolder) {
setProjectView((ProjectViewHolder) holder, position);
}
}
答案 0 :(得分:0)
好吧,onBindViewHolder
没有任何问题,它只会改变视图值。我认为您的问题是您不完全了解RecyclerView的工作原理。
getItemCount
getItemViewType
)onBindViewHolder
的数据。因此,如果您有4个可见项目,onBindViewHolder
将被调用4次。
当一个项目变为可见时,或者当您使用notifyDataSetChanged
告诉适配器数据发生更改时,将调用此方法。这没有任何问题,我认为你有类型的问题。 顺便说一句,你有一些其他更具体的方法可以在数据发生变化时阻止适配器:
- final void notifyItemChanged(int position)
Notify any registered observers that the item at position has changed.
- final void notifyItemChanged(int position, Object payload)
Notify any registered observers that the item at position has changed with an optional payload object.
- final void notifyItemInserted(int position)
Notify any registered observers that the item reflected at position has been newly inserted.
- final void notifyItemMoved(int fromPosition, int toPosition)
Notify any registered observers that the item reflected at fromPosition has been moved to toPosition.
- final void notifyItemRangeChanged(int positionStart, int itemCount)
Notify any registered observers that the itemCount items starting at position positionStart have changed.
- final void notifyItemRangeChanged(int positionStart, int itemCount, Object payload)
Notify any registered observers that the itemCount items starting at positionpositionStart have changed.
- final void notifyItemRangeInserted(int positionStart, int itemCount)
Notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted.
- final void notifyItemRangeRemoved(int positionStart, int itemCount)
Notify any registered observers that the itemCount items previously located at positionStart have been removed from the data set.
- final void notifyItemRemoved(int position)
Notify any registered observers that the item previously located at position has been removed from the data set.
官方RecyclerView.Adapter文档here。