【问题标题】:Android - How to update my recyclerview from another fragment in a viewpager?Android - 如何从 viewpager 中的另一个片段更新我的 recyclerview?
【发布时间】:2016-10-25 06:12:01
【问题描述】:
所以我在标签布局中有 2 个片段。我使用 viewpager 来设置它。
在第一个片段中,我有一个充满数据的回收器视图。在第二个片段中,我有一个微调器。
当用户在微调器中选择某些内容时,应根据选择使用新数据更新 recyclerview。
我如何才能在第二个片段中实现这一点,用户从微调器中选择一个选项,而不是滑回第一个片段并且 recyclerview 已经使用新数据更新?
谢谢!
【问题讨论】:
标签:
java
android
android-fragments
android-recyclerview
spinner
【解决方案1】:
你可以用不同的方式做到这一点:
-
使用
Intent
并在其中添加一些额外的内容:
Intent intent = new Intent();
intent.putExtra("foo",somevalue);
然后发送它
sendBroadcast(intent)
您的接收器类只需扩展
BroadcastReceiver
对数据进行分类和更新
onReceive
方法。
public class receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//manipulate your data
}
}
记得注册你的接收器
使用包含您的数据的Singleton Class。因此,您可以从第一个片段中设置数据(在微调器选择之后)并从第二个片段中获取数据(在onCreate() 方法中)
【解决方案2】:
将RecyclerView的适配器和数据列表放在父activity中而不是fragment中。在Spinner 的onItemSelected() 中,调用adapter.notifyDatasetchanged(或notifyItem(Range)Inserted/Changed/Removed())。
如果您有大量的片段间通信,一个非常简单的方法是实现 EventBus (https://github.com/greenrobot/EventBus)。在 EventBus 上注册这两个 Fragment,当在 Fragment B 的 spinner 中选中一个 item 时,发送 SpinnerItemSelected 事件。如果 Fragment A 在总线上注册了它就会收到它,您可以在收到它时拨打notifyDatasetChanged()。