简体   繁体   中英

How to refresh recyclerview adapter when data changes in other fragment?

First 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);
   } 
}

In the first fragment i have a recyclerview which displays a list with all songs found on the device and i have an option to delete a song which changes the data in my arraylist Main.musicList by rescanning all songs on the device.

So all my other arraylists in my app still have a reference to that deleted song.

So how can i call notifySetDataChanged on all recyclerview adapters in other fragments when i delete an item in the first fragment?

The easy way will be to use BroadcastReceiver . try this answer

  1. Use ViewModel in your Activity which holds these fragments.

  2. Wrap your song list in LiveData object. This can be observed by all of your fragments depending on their lifecycle (when the fragment is in OnResumed state, it will be automatically notified when your list has changed)

  3. In related fragment start to observe LiveData and on change update your adapter.

Related topics: https://developer.android.com/topic/libraries/architecture/livedata https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54 Hope I could help you.

您可以使用EventBus触发该方法,通过该方法将通知reyclcer视图适配器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM