第一个 fragment
private void initRecyclerView() {
Main.musicList = Main.songs.songs;
if ((Main.musicList != null) && (!Main.musicList.isEmpty())) {
// Connects the song list to an adapter
// (Creates several Layouts from the song list)
allSongsAdapter = new AllSongsAdapter(getActivity(), Main.musicList);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerViewSongs.setLayoutManager(linearLayoutManager);
recyclerViewSongs.setHasFixedSize(true);
recyclerViewSongs.setAdapter(allSongsAdapter);
}
}
在第一个 fragment 中,我有一个 recyclerview,它显示一个列表,其中包含设备上找到的所有歌曲,并且我可以选择删除一首歌曲,该歌曲会通过重新扫描来更改我的数组列表 Main.musicList 中的数据设备上的所有歌曲。
因此,我的应用程序中的所有其他数组列表仍然引用了该已删除的歌曲。
那么当我删除第一个 fragment 中的项目时,如何在其他 fragment 中的所有recyclerview适配器上调用notifySetDataChanged?
最佳答案
在您的 Activity 中使用 ViewModel 来保存这些 fragment 。
将歌曲列表包装在 LiveData 对象中。这一点大家都可以观察到 fragment 的数量取决于它们的生命周期(当 fragment 是 在 OnResumed 状态下,当您的列表 已更改)
- 在相关 fragment 中开始观察LiveData等 更改更新您的适配器。
相关主题: https://developer.android.com/topic/libraries/architecture/livedata https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54 希望我能帮助你。
关于java - 当其他fragment中的数据发生变化时如何刷新recyclerview适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54844650/