[英]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. 在第一个片段中,我有一个recyclerview,该视图显示一个列表,其中包含在设备上找到的所有歌曲,并且我可以选择删除一首歌曲,该歌曲通过重新扫描设备上的所有歌曲来更改阵列列表Main.musicList中的数据。
So all my other arraylists in my app still have a reference to that deleted song. 因此,我的应用程序中的所有其他arraylist仍具有对该删除歌曲的引用。
So how can i call notifySetDataChanged on all recyclerview adapters in other fragments when i delete an item in the first fragment? 那么,当我删除第一个片段中的项目时,如何在其他片段中的所有recyclerview适配器上调用notifySetDataChanged?
Use ViewModel in your Activity which holds these fragments. 在保存这些片段的Activity中使用ViewModel。
Wrap your song list in LiveData object. 将歌曲列表包装在LiveData对象中。 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) 您的所有片段均可根据其生命周期进行观察(片段处于OnResumed状态时,列表更改时将自动通知该片段)
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. 相关主题: https : //developer.android.com/topic/libraries/architecture/livedata https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54希望我能为您提供帮助。
您可以使用EventBus触发该方法,通过该方法将通知reyclcer视图适配器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.