java - 当其他fragment中的数据发生变化时如何刷新recyclerview适配器?

标签 java android android-recyclerview

第一个 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?

最佳答案

  1. 在您的 Activity 中使用 ViewModel 来保存这些 fragment 。

  2. 将歌曲列表包装在 LiveData 对象中。这一点大家都可以观察到 fragment 的数量取决于它们的生命周期(当 fragment 是 在 OnResumed 状态下,当您的列表 已更改)

  3. 在相关 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/

相关文章:

java - 如何更改 ResponseEntity 中的 JSON 响应格式?

java - Java中使用泛型动态返回调用类的类型

java - 如何在 Mapbox 导航应用程序 (android) 中添加地点插件?

android - xamarin 在 mac 上构建的 APK 未安装

android - RecyclerView 中的共享元素过渡

android - Recycler view with volley 图像请求(取消请求)

java - JAVA 中的元素顺序(导入 javax.xml.*)

java - 这两个 Java 数组是否相同?

android - BaseFragmentActivityApi16.startActivityForResult(intent, int, Bundle) 在面向 Android O 时抛出错误

android - 带有 CardView 的 RecyclerView 在滚动时滞后