简体   繁体   中英

How to pass data from Fragment A to Fragment B if fragments already include a Bundle?

I want to get String value, changed dynamically by user's press on Spinner in Fragment, to another Fragment. So I was trying to find an answer and I found two: Interface and Bundle. It seems, in my case, the question is too specific and I don't know how to figure it out. The Interface option seems to be the choice at first but how to pass data dynamically (event created by user) over the interface? The Bundle on the other hand gets me confused in yet different way.

All my fragments, there is 4 of them, are declared explicitly like this:

public class MyFragment extends Fragment{

private static final String FRAG_TAG = "my_fragment";
private static UUID mId = UUID.randomUUID();
private UUID getID(){return mId;}

...          

public static MyFragment newInstance(){

    MyFragment sMyFragment  = new MyFragment ();
    final Bundle args = new Bundle();
    args.putSerializable(FRAG_TAG, mId);
    sMyFragment.setArguments(args);
    return sMyFragment;}

public MyFragment (){} //empty constructor

...

}

and initialized in onCreate in my MainActivity, which is the container for all of 'em, like this:

  getSupportFragmentManager().beginTransaction()
            .add(R.id.my_fragment, MyFragment.newInstance(), "my_fragment").commit();

From then on I only show/hide those fragments which means the Bundle stays the same. So how can I add a Bundle to a fragment that has a Bundle with it, and is initialized only once, without creating newInstance() of it?

Please include example code. Thanks.

在这种情况下,您可以使用EventBus看看: https : //github.com/greenrobot/EventBus

The Bundle option doesn't really help here, it is meant for when you create a Fragment and want to pass it some data to begin with (data is known when Fragment is created).

You probably want to pass that data via your containing Activity, I'll outline this (code is not complete / error free):

Create a callback interface like

interface Callback{
   void selectionMade(Data data)
}

Pass callback to Fragment that should 'send' data, your Activity might implement the callback like:

MyFragment myFragment = MyFragment.instance()
myFragment.setCallback(this)

or with an anonymous class:

myFragment.setCallback(new Callback(){
   void selectionMade(Data data){

         otherFragment.setData(data)

   }
})

In the Fragmend that 'sends' data, invoke callback whenever you want (eg user selected spinner):

callback.selectionDone(data)

When callback is invoked, Activity informs 'receiving' Fragment of the data (see anonymous class example above).

If you have a lot of communication between your Fragments, you might want to consider using some sort of Event bus

The EventBus turns out to be the answer. Thanks for replays. For anyone concern with same problem here's how I did it.

Default class for EventBus.

public class EventBus {    

private static EventBus mEventBus = new EventBus();

public static EventBus getEventBus() {
    return mEventBus;

  }
} 

Example class that sets and gets values for EventBus to pass. In my case Strings:

public class SomeValue{

private String name = "value";

public SomeValue(String string){name = string;}

public String getName() {return name;}

public void setName(String string) {this.name = string;}
}

Implementation of the EventBus in fragment that sends the data. In my case in onClick listener for Button:

...

@Override
        public void onClick(View view) {
            SomeValue message = new SomeValue("");
            GlobalEventBus.getEventBus().post(message);
        }

And finally @Subscribe annotation in fragment that receives and prints the data:

...

@Subscribe
public void onEventReceived(SomeValue message){        
    setText(message.getName());
}
...

public void setText(String text){  
 //setText method (in the same fragment) bidden to TextView that prints the "message" given by EventBus
    TextView textView = (TextView) getActivity().findViewById(R.id.my_view);
    textView.setText(text);
}

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