简体   繁体   English

从其他片段更新 recyclerview 适配器

[英]Update recyclerview adapter from other fragment

I have a model which is a list of objects and the object contains like_count我有一个 model 这是一个对象列表,object 包含 like_count

The home page has a adapter of the model主页有model的适配器

onclick of an item traversing to other fragment, if like is clicked in the fragment like count is increased but when user comes back the homepage should reflect the updated like count onclick遍历到其他片段的项目,如果在片段中单击喜欢计数会增加但当用户返回主页时应反映更新的喜欢计数

also cannot use singleton class as the same model is used on various fragments.也不能使用 singleton class 因为相同的 model 用于各种片段。

Now I am using broadcast listener but the performance is going slow,现在我正在使用广播侦听器,但性能变慢了,

Could anyone please help on this.有人可以帮忙吗?

Assuming that you are using non-observable data source, the fragment which applies changes should notify caller fragment somehow.假设您使用的是不可观察的数据源,应用更改的片段应该以某种方式通知调用者片段。 You can use setTargetFragment / onActivityResult function pair to return data from called fragment.您可以使用setTargetFragment / onActivityResult function 对从调用的片段返回数据。 In this case you can return a boolean flag indicating that there was a change, and caller fragment should check it and reload data if necessary.在这种情况下,您可以返回一个 boolean 标志,指示发生了变化,调用者片段应该检查它并在必要时重新加载数据。

I'd strongly suggest checking out Android Jetpack , and in particular the Android ViewModel and LiveData libraries, which let you manage data for an Activity, including across many child fragments.我强烈建议您查看Android Jetpack ,尤其是 Android ViewModelLiveData库,它们可让您管理 Activity 的数据,包括跨许多子片段的数据。 This is likely what @Miha_x64 was referring to with an 'observable data source' - the ViewModel allows you to declare and managed shared data (LiveData) across fragments, and allows those fragments to update the shared data and respond to changes.这很可能是@Miha_x64 所指的“可观察数据源”——ViewModel 允许您跨片段声明和管理共享数据 (LiveData),并允许这些片段更新共享数据并响应更改。

Whether or not you decide to go with the ViewModel, there's a really good page of Android documentation that talks about communicating across fragments, I'd suggest starting there: https://developer.android.com/training/basics/fragments/communicating Whether or not you decide to go with the ViewModel, there's a really good page of Android documentation that talks about communicating across fragments, I'd suggest starting there: https://developer.android.com/training/basics/fragments/communicating

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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