RecyclerView - 通过布尔值控制项目计数

RecyclerView - control item count by boolean

我正在使用 RecyclerView,其中 getItemCount() 涉及一个布尔值。这个布尔值控制 RecyclerView 中最后一项的可见性,有点像加载更多视图,但略有不同。这个布尔值会不时发生变化,因此 RecyclerView 将知道是否包含最后一项。

代码看起来像这样

@Override
public int getItemCount() {
    return mItemArray.size() + (shouldShow ? 1 : 0); 
}

shouldShow 的值更新时,我没有调用 notifyDataSetChanged()notifyItemChanged(),但 RecyclerView 仍然正确更新。但我担心它最终会导致 RecyclerView 由于不一致而崩溃。我的问题是,

  1. getItemCount() 中使用动态布尔值是否是控制 RecyclerView 大小的正确方法?
  2. 当这个布尔值改变时,我应该调用 notify...() 吗?
  3. 我的 RecyclerView 会因为不一致而崩溃吗?

1.not 一个问题,直到你在其中传递 int 2.there 不需要调用 notifydatasetchanged(我们应该在适配器数据发生变化时调用它们) 3.there不会有任何一致性

1.It没问题
2.If 您希望在布尔变量更改后立即显示最后一项,您应该调用 notifyDataSetChanged(),因为在滚动回收器视图之前适配器不会调用 getItemCount()
3.The 如果您不处理所有行为,应用程序可能会崩溃。例如,您在 onBindViewHolder() 方法中从 mItemArray 中取出一些项目,当 getItemCount() returns 的数字大于数组的大小时,应用程序将抛出 IndexOutOfBoundException.在这种情况下,您应该检查位置是否小于数组的大小。

if (position < mItemArray.size()){
    //you can get item from the array
} else {
    //handle your additional item
}