我有这样的问题。我有一个简单的壁纸应用程序。
我从 API
获取壁纸,有一个名为 Category
的 Tab
,其中我有 Sections
我想在 Category
Tab
中隐藏一些 Sections
。
在最好的情况下,我的后端开发人员必须从后端隐藏或删除它,但因为他现在不可用。我决定自己做。
因此,在 RecyclerView
中的 Category
Tab
中 onBindViewHolder
我正在检查标题是否与标题相同我想删除我正在调用 removeAt
(您可以在下面看到该部分):
if (categoryTitle.equals("Hot")) {
list.removeAt(holder.layoutPosition)
}
我需要在 Category
Tab
显示时调用它,这样用户将无法看到 Category
部分
。但它不会更新它,因为我也必须调用这两种方法:
if (categoryTitle.equals("Hot")) {
list.removeAt(holder.layoutPosition)
notifyItemRemoved(holder.layoutPosition)
notifyItemRangeChanged(holder.layoutPosition, list.size)
}
但是在调用他们时我得到了一个错误提示
“当 RecyclerView 正在计算布局或滚动时无法调用此方法……”
问题来了。 我必须在哪里调用它以避免错误?
(我的应用程序链接: https://play.google.com/store/apps/details?id=com.backpaper )
(请不要建议使用计时器或延迟或类似的东西 (-_-)
)
更新:
override fun onResponse(categories: Categories) {
categories.categories!!.removeAt(5)
categories.categories!!.removeAt(1)
adapter = RecyclerViewAdapterC(categories.categories!!)}
最佳答案
不要在 onBindViewHolder()
中删除项目它会抛出异常,因为项目尚未添加。异常(exception)情况如下。
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
在将项目添加到适配器之前,您应该从数据集中删除该项目。
if (!categoryTitle.equals("Hot")) {
// Add item else do not add item
}
过滤列表数据集后,然后使用过滤列表设置适配器。
下面是一个例子。
ArrayList<String> list=new ArrayList();
for(String cat : categories.categories){
if (!categoryTitle.equals("Hot")) {
list.add(cat);
}
}
adapter = RecyclerViewAdapterC(list)
关于android - NotifyItemRemoved 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49455555/