【问题标题】:Android: Suggestion required for Update recycler view on item selected from spinnerAndroid:从微调器中选择的项目上更新回收器视图所需的建议
【发布时间】:2016-03-07 12:25:12
【问题描述】:

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

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

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

所以,我怀疑我是否正确地在onItemSelected() 中通知回收器视图适配器的微调器,或者应该更改它。

附:我尝试关注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

【问题讨论】:

    标签: android android-recyclerview


    【解决方案1】:

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

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

    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 当然。没问题。
    【解决方案2】:

    首先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() 是完全可以的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 2016-05-19
      • 2021-05-29
      相关资源
      最近更新 更多