Android:从下拉菜单中选择项目后更新回收视图需要建议

8

我对RecyclerView不太熟悉。我的需求如下: - 我需要调用一个Web服务,该服务将提供两个数组。一个是我需要在列表中显示的数据。为此,我正在使用RecyclerView。另一个数组是状态,我将其显示在下拉菜单中。这个Web服务是分页的。我已经添加了分页,并且它正常工作。 - 当用户从下拉菜单中选择其他元素时,我必须再次调用Web服务,并且RecyclerView数据应更改。 目前,在分页的情况下,我执行以下操作,一旦我从连续的页面获取更多数据:

mAccountListingsAdapter.notifyItemRangeInserted(mAccountListingsAdapter.getItemCount(), mListings.size() - 1);

当我从下拉菜单中更改数据时,我正在执行以下操作:

mListings.clear();//Clear the data set

mAccountListingsAdapter.notifyDataSetChanged();//Call notify data set changed on recycler view adapter

getAccountListings();//Fetch new data from the web service and display in recycler view

然而,建议不要直接在recycler view adapter上调用notifyDataSetChanged()方法,而是应该调用特定的notifyXXX方法,以避免性能和动画问题。

因此,我有疑虑,是否正确在下拉列表的onItemSelected()方法中通知recycler view adapter,或者应该进行更改。

附注:我尝试在onItemSelected()方法中执行以下操作:

int size = mListings.size();
mListings.clear();
mAccountListingsAdapter.notifyItemRangeRemoved(0, size - 1);

但是它崩溃了,并出现以下异常:

03-02 12:59:41.046: E/AndroidRuntime(4270): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 4(offset:0).state:5
2个回答

4

我认为notifyItemRangeRemoved是这里应该使用的正确方法,但您传递的第二个参数值是错误的。根据文档,第二个参数是从数据集中删除的项目数,而您传递的是最后一个已删除项目的位置。

enter image description here

所以下面的代码应该可以正常工作。
int size = mListings.size();
mListings.clear();
mAccountListingsAdapter.notifyItemRangeRemoved(0, size);

更多信息请参考:http://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyItemRangeRemoved(int,%20int)


+1 我的错误 Abhishek - 我开始写我的答案,然后休息了一下才最终发布。我没有意识到可能有其他人在此期间已经发布了答案。目前,我会保留发布该答案以提供其他信息。 - Vikram
@Vikram 当然,没问题。 - Abhishek V

1

首先,notifyItemRangeRemoved(int, int) 的方法定义为:

public final void notifyItemRangeRemoved (int positionStart, int itemCount)

第二个参数是count,而不是positionEnd。在您的情况下,您将size - 1作为第二个参数传递,而应该是size本身。
int size = mListings.size();
mListings.clear();
// should be notifyItemRangeRemoved(0, size)
mAccountListingsAdapter.notifyItemRangeRemoved(0, size - 1);

其次,notifyDataSetChanged() 不太受欢迎,因为它会触发所有可见视图的重新绑定和重新布局。在您的情况下,如果可见项数量为零,我不明白为什么 notifyDataSetChanged() 会降低性能。如果您正在动画移除项目,请使用 notifyItemRangeRemoved(0, size)。否则,在这里使用 notifyDataSetChanged() 是完全可以的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接