【问题标题】:I can't figure out why my adapter is not updating my recyclerview我不知道为什么我的适配器没有更新我的 recyclerview
【发布时间】:2016-07-23 23:32:11
【问题描述】:

我已经阅读了一些类似的问题,并且我试图让它工作,但我不明白为什么我的适配器在我的 SaveItem 活动返回后没有更新我的 recyclerview。所以我有两个标签:所有笔记和收藏笔记。更具体地说:App image .

当我从底部按下浮动操作按钮时,它会启动一个新活动,我可以在其中记录新笔记,但是当我返回 MainActivity 第一个片段时,它不会更新我的回收站视图:

这是我填充适配器的地方:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    adapter = new NoteAdapter(fillAdapter(),this,getActivity());
    recycler.setAdapter(adapter);
    recycler.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
}

这是我尝试更新我的回收站视图的地方:

@Override
public void onResume() {
    super.onResume();
    adapter.addAll(fillAdapter());
    recycler.setAdapter(adapter);
}

这是我的addAll 方法:

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolderNote> {
    // Other codes....
    public void addAll(List<Note> newNotes) {
        this.notes.clear();
        this.notes.addAll(newNotes);
        this.notifyDataSetChanged();
    }
}

【问题讨论】:

  • 你能发布你的 fillAdapter() 函数吗?以及如何在第二个活动中向 List 添加另一个项目?

标签: android tabs fragment android-recyclerview onresume


【解决方案1】:

Fragment 班级中列出Note

private List<Note> allNotes;

然后在你的onActivityCreated里面

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    allNotes = fillAdapter();

    adapter = new NoteAdapter(allNotes, this, getActivity());
    recycler.setAdapter(adapter);
    recycler.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
}

现在要更新您的列表,再次调用fillAdapter 函数以再次填充allNotes 列表并像这样修改您的onResume

@Override
public void onResume() {
    super.onResume();
    allNotes = fillAdapter();
    adapter.notifyDatasetChanged();
}

addAll 函数现在没有必要。从您的NoteAdapter 中删除该功能。

关键是传递给适配器的列表的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 2020-09-23
    相关资源
    最近更新 更多