24 June 2015

Trying out Android EventBus

EventBus is a open-source library which simplifies communication between components in Android applications.

To add EventBus to the project using gradle, add this line to build.gradle:
compile 'de.greenrobot:eventbus:2.4.0'

In our example we want to send a message from an activity to a fragment. The message needs to be in the format of a class, so let us create an event class which holds the message we want to send:

The main activity’s layout contains: An EditText, a button, a label and a fragment.
The fragment contains a label and a TextView.

In the main activity we create an event and send our message:

To be able to listen to events the fragment has to register itself and then it can receive events in onEventMainThread:

 

Repository on GitHub