Android 在 RecyclerView 中添加/替换项目

标签 android android-recyclerview android-adapter notifydatasetchanged

我知道已经有很多关于这个主题的话题,但到目前为止,没有一个给定的解决方案对我有用。我正在尝试添加或更新 RecyclerView 的项目。到目前为止,这是我的代码:

主 Activity

private MyListItemAdapter mAdapter;
private RecyclerView recyclerView;

// called on activity create
private void init() {
    // initialize activity, load items, etc ...
    mAdapter = new MyListItemAdapter(this, items);
    recyclerView.setAdapter(mAdapter);
}

// called when I want to replace an item
private void updateItem(final Item newItem, final int pos) {
    mAdapter.replaceItem(newItem, pos);
}

MyListItemAdapter

public class MyListItemAdapter extends RecyclerView.Adapter<MyListItemAdapter.MyListItemViewHolder> {

    private List<Item> mItems;

    public void replaceItem(final Item newItem, final int pos) {
        mItems.remove(position);
        mItems.add(position, newItem);

        notifyItemChanged(position);
        notifyDataSetChanged();
    }    
}

我也尝试从 MainActivity 进行此更改,但在我尝试过的每种情况下,我的列表都没有更新。它工作的唯一方法是当我将适配器重置为 recyclerView 时:

mAdapter.notifyDataSetChanged();
recyclerView.setAdapter(mAdapter);

这显然是个坏主意。 (除了不好的副作用,当我在我的列表上使用延迟加载时甚至都不起作用)。

所以我的问题是,如何让 notifyDataSetChanged() 正常工作?

编辑

我找到了替换元素的解决方案。在 mAdapter.replaceItem(newItem, pos); 之后,我不得不调用 recyclerView.removeViewAt(position);

这适用于替换项目,但当我想将项目(例如延迟加载)添加到我的列表时不能解决我的问题

edit2

我找到了添加项目的有效解决方案

适配器:

public void addItem(final Item newItem) {
    mItems.add(newItem);
    notifyDataSetChanged();
}

Activity :

private void addItem(final Item newItem) {
    mAdapter.addItem(newItem);
    recyclerView.removeViewAt(0); // without this line nothing happens
}

出于某种原因,这可行(另外:它不会删除位置 0 处的 View ),但我确定这不是将项目添加到 recyclerView 的正确方法

最佳答案

这应该有效:

private ArrayList<Item> mItems;

public void replaceItem(final Item newItem, final int position) {
    mItems.set(position, newItem);
    notifyItemChanged(position);
}  

ArrayList.set() 是替换项的方法。

要添加项目,只需将它们附加到 mItems,然后转到 notifyDatasetChanged()。另一种方法是使用 notifyItemRangeInserted()。根据您添加新项目的位置/方式以及其中的数量,这可能是值得的。

关于Android 在 RecyclerView 中添加/替换项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33411903/

相关文章:

java - Android中如何保存ListView的值

Android:如何制作一个看起来类似于 Preferences 的 ListView?

java - 阻止用户多次单击 edittext 以打开多个对话框

android - Feed 广告中的 Facebook Native 在 RecyclerView 中相互重叠

android - RecyclerView 焦点滚动

android - 升高的 RecyclerView 项目逐渐变形(海拔变化)

java - RecyclerView 项目,包含来自多个 arrayList 的数据,在 fragment 重新启动时重复

android - 如何获取已安装的应用程序图标并使其可用于 gridView

android - 如何在删除从 recyclerview 适配器打开的 Activity 时更新 recyclerview

android - 如何区分 TextWatcher 中的用户输入和 setText 方法?