Skip to content Skip to sidebar Skip to footer

Multiple Fragment To Activity Communication

here we go again. I am writing an app using fragments. Stefan de Bruijn suggested this would be better than using the deprecated TabHost and he was right, Thank you Stefan. I have

Solution 1:

For communication between fragments you can use an EventBus. The EventBus makes your activity and fragments loosly coupled.

The first step is defining an EventType. For example: CarSelectedEvent

Upon selection of a Car (or some text type in your case) the CarSelectedEvent must be posted on the EventBus. Example:

eventBus.post(newCarSelectedEvent("volvo"));

All fragments or activities interested in the Event have to implement a method called:

onEvent(CarSelectedEvent event){
... update your view
}

Assume your have 3 fragments showing car details, each fragment receives the CarSelectedEvent and can update the view. When removing a fragment from the screen (for example on a smaller screen or a screen rotation) the logic does not change. The only difference is less fragments receiving the event.

You can find more information about EventBus on https://github.com/greenrobot/EventBus.

Post a Comment for "Multiple Fragment To Activity Communication"