![](/img/trans.png)
[英]onBindViewHolder not called after RecyclerView Adapter notifyDataSetChanged()
[英]RecyclerView changes it's position value in onBindViewHolder after 2-3 notifyDataSetChanged is called
我通過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);
}
}
好吧, 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文檔在此處 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.