【问题标题】:How to refresh only one section of list in recyclerview如何在recyclerview中仅刷新列表的一部分
【发布时间】:2023-03-11 01:35:01
【问题描述】:

我有复杂的RecyclerView,我正在使用带有 5 个ViewHolders 的适配器。我创建了类似于联系人列表的自定义部分。但在我的 recyclerView 中,一个部分的项目可以重置另一部分中的所有内容。但我不知道该怎么做。

我现在正在做的是擦除整个适配器列表并再次添加项目,这不是有效的方法。 Section 1 中的项目也包含 CheckBox,如果选中,它可以清除 Section 2Section 3 中的所有数据。

OnCheckedChangeListenerCheckBox 状态从itemList[pos] 状态的设置在onBindViewHolder 内设置(在绑定开始时检查节内的默认选中项)。如果选中设置为 true,它将刷新整个列表并调用 notifyDataSetChanged这是因为不同部分中的所有其他项目都基于第一部分中的选中项目。

由于concurrent modification exception,这会导致崩溃。每次这些项目之一在onBindViewHolder 内再次绑定时,都会触发检查更改侦听器并刷新整个列表。如果连续调用 2 次或更多次,它会使我的应用程序崩溃。 此外,如果用户将向上和向下滚动并且 Section1 项目开始重新出现和消失,它将连续多次调用 onBindViewHolder => notifyDataSetChanged() 被多次调用 => 异常。

Android RecyclerView 确实缺乏对部分的原生支持。像 subArrays 这样在开始时设置部分然后调用adapter.updateSection(1) 是非常酷的。

如果我可以为每个部分单独创建RecyclerView,这也会更好,但是整个 RecyclerView 必须是可滚动的。在NestedScrollView 中添加4 个RecyclerViews 将杀死回收机制。

刷新项目的代码预览:

val selectedVariantFirstSectionJSONObject = getSelectedVariantInJSON(selectedVariantID)
        ingredientsItemList.apply {
            clear()
            add(IngredientHeaderItemNonIconified(getString(R.string.food_ingredients_variant_label)))
            addAll(foodVariantsArray)
            add(IngredientSectionSeparator())
            add(IngredientHeaderItemNonIconified(getString(R.string.food_ingredients_required_ingredients_label)))
            add(RequiredIngredient(getVariantRequiredIngredients(selectedVariantJSONObject.getJSONArray(getString(R.string.food_variant_required_ingredients)))))
            add(IngredientSectionSeparator())
            add(IngredientHeaderItemIconified(getString(R.string.food_ingredients_remove_ingredients_label), TYPE_INGREDIENT_REM))
            addAll(removableIngredients)
            add(IngredientSectionSeparator())
            add(IngredientHeaderItemIconified(getString(R.string.food_ingredients_add_ingredients_label), TYPE_INGREDIENT_OPT))
            addAll(optionalIngredients)
        }

adapter.notifyDataSetChanged()

图片便于理解(有点复杂):

【问题讨论】:

    标签: android android-layout android-recyclerview


    【解决方案1】:

    您可以直接拨打RvAdapter.notifyItemRangeChanged(start,count); 如果你有

    ,子适配器也是一样的

    【讨论】:

      【解决方案2】:

      如果您有修改过的项目位置,那么只需传递那些, 在具有修改数据位置的列表的循环中运行以下方法。

       public void updateItem(Data Data, int position) {
              mDataList.add(position, data);
              notifyItemChanged(position);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-24
        • 2014-12-23
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        相关资源
        最近更新 更多