Skip to content

Activity and Fragment

Daniel Bergløv edited this page Oct 25, 2015 · 1 revision

Back to Home


When working with Fragments, one of the most important things is being able to communicate between them and their Activity. Since Fragments can be very dynamic in nature, two fragments should never communicate directly with one another, but instead use a form of message system. Google has made an attempt of such system by introducing the LocalBroadcastManager. But like the regular broadcast service it is a pain to setup since it requires creating and registering each receiver for each Fragment and Activity.

To make this much simpler and more automated, UtilsLib comes packed with MsgActivity, MsgFragment, MsgFragmentDialog and MsgContext.

Example 1

public class MyActivity extends MsgActivity {
    @Override
    public void onResume() {
        sendMessage(1, "key", true);
    }
}

public class MyFragment extends MsgFragment {
    @Override
    public void onReceiveMessage(int type, HashBundle data, boolean isSticky) {
        switch (type) {
            case 1: 
                if (data.getBoolean("key", false)) {
                    // Do something
                }
        }
    }
}

The message sent from the Activity will be parsed to all active fragments. Messages can also be sent from a Fragment and also be received by the Activity.

If you need to send or receive messages from external sources like a local service, you can use the MsgContext. This is a Context Wrapper built with the same message options as the Activity and Fragment classes.

Example 2

MsgContext msgContext = new MsgContext(context);

// Send a message from any available context
msgContext.sendMessage(1, "key", true);

// Setup this Context Wrapper to receive messages
msgContext.setMsgListener(new MsgListener(){
    @Override
    public void onReceiveMessage(int type, HashBundle data, boolean sticky) {
        // Handle messages
    }
});

/* Remember to remove the listener once done. 
 * When setting a listener, the MsgContext class will register a 
 * broadcast receiver. By parsing `NULL` that receiver will be unregistered. 
 */
msgContext.setMsgListener(null);