我知道已经有很多关于这个主题的话题,但到目前为止,没有一个给定的解决方案对我有用。我正在尝试添加或更新 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/