Android:从微调器中选择的项目更新回收器视图所需的建议

Nit*_*ish 8 android android-recyclerview

我是回收者视图的新手.我的要求如下: - 我必须调用一个将提供两个数组的Web服务.一个有我需要在列表中显示的数据.为此目的,我正在使用RecyclerView.另一个数组是状态,我在spinner中显示.此Web服务是分页的.我添加了分页,它工作正常. - 当用户从微调器中选择一些其他元素时,我必须再次进行Web服务调用,并且回收器视图数据应该更改.目前,在分页的情况下,一旦我从连续页面获得更多数据,我正在进行跟踪:

mAccountListingsAdapter.notifyItemRangeInserted(mAccountListingsAdapter.getItemCount(), mListings.size() - 1);
Run Code Online (Sandbox Code Playgroud)

而且,当我从微调器更改数据时,我正在做以下事情:

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
Run Code Online (Sandbox Code Playgroud)

但是,建议不要直接在recycler视图适配器上调用notifyDataSetChanged(),而应调用特定的notifyXXX方法,以避免性能和动画问题.

所以,我有疑问,如果我正确地通知onItemSelected()微调器中的recycleler视图适配器,或者它应该被更改.

PS我试过以下onItemSelected:

int size = mListings.size();
mListings.clear();
mAccountListingsAdapter.notifyItemRangeRemoved(0, size - 1);
Run Code Online (Sandbox Code Playgroud)

但随后它崩溃了,但有以下例外:

03-02 12:59:41.046: E/AndroidRuntime(4270): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 4(offset:0).state:5
Run Code Online (Sandbox Code Playgroud)

Abh*_*k V 4

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

在此输入图像描述

所以下面的代码应该可以正常工作

int size = mListings.size();
mListings.clear();
mAccountListingsAdapter.notifyItemRangeRemoved(0, size);
Run Code Online (Sandbox Code Playgroud)

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