在不使用活动的情况下在两个片段之间传递数据 [英] Pass data between two fragments without using activity
问题描述
我想在不使用活动和片段活动的情况下在两个片段之间传递数据.
I want to pass data between two fragments without using activity and fragment activity.
我不想使用这样的活动在片段之间传递数据:Communicating与其他片段
I don't want to pass data between fragments using activity like this : Communicating with Other Fragments
以下是我的场景:
我有一个父片段,里面有两个子片段.现在我需要在这两个片段之间传递数据.如何实现?
I have one Parent fragment and inside that there are two child fragments.Now my need is to pass data between these two fragments.How to achieve this?
我研究了这个:事件总线但没有得到片段的工作示例.
I looked into this : Event Bus but not getting working example for fragments.
是否有其他替代方法可以在片段之间传递数据?
Is there any other alternative to pass data between fragments?
任何帮助将不胜感激.
根据 InnocentKiller 的回答进行
在 FragmentOne 中,我实现了:
In FragmentOne , I have implemented :
FragmentTwo = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("Hello", "My name is Siddharth");
fragment.setArguments(bundle);
在 FragmentTwo 中,我实现了:
In FragmentTwo, I have implemented :
Bundle bundle = this.getArguments();
String myInt = bundle.getString("Hello","Test");
mStartTripButton.setText(myInt);
推荐答案
在activity/fragment、fragment/fragment/、activity/activity、class/class之间交换数据的最佳方式,制作一个通用的单例类,如:
Best Way to exchange data between activity/fragments, fragment/fragment/, activity/activity, class/ class, make a common singleton class like:
public class DataHolderClass {
private static DataHolderClass dataObject = null;
private DataHolderClass() {
// left blank intentionally
}
public static DataHolderClass getInstance() {
if (dataObject == null)
dataObject = new DataHolderClass();
return dataObject;
}
private String distributor_id;;
public String getDistributor_id() {
return distributor_id;
}
public void setDistributor_id(String distributor_id) {
this.distributor_id = distributor_id;
}
}
现在可以在移动到新屏幕之前在任何事件的任何地方(片段、活动、类)进行设置
DataHolderClass.getInstance().setDistributor_id("your data");
现在去任何地方(片段,活动,类)
String _data = DataHolderClass.getInstance().getDistributor_id();
这篇关于在不使用活动的情况下在两个片段之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!