Android Coder: Using Callbacks For Activity-Based Actions

Because Android applications are designed to run on phones, tablets and other types of platforms, fragments should be built as independent units, directed by Activities which perform actions based on the application’s environment. To maintain that independence we can delegate work back to the hosting activity by defining callbacks in our fragments.

When the user clicks on one of the links in NixMashupLinks for Android we use callbacks so that the action is performed in the host activity. This allows us, for instance, to display the link detail fragment on its own screen, in a separate column or some other location.

In NixMashupLinks our List Fragment class is and our hosting activity class is, so we begin by adding the Interface to

To implement our Callbacks interface we first define a member variable to hold the object that implements Callbacks. We then cast the hosting activity to Callbacks and assign it to that variable.

Still in our LinkListFragment class…

private Callbacks mCallbacks;

then we’ll override onAttach(Activity) and onDetach() to set and unset it.

Now LinkListFragment has a way to call methods on its hosting activity, LinkListActivity. Everything in LinkListFragment will work the same for any hosting activity as long as the activity implements LinkListFragment.Callbacks.

We’ll move to LinkListActivity in a second, but first we’ll see how we call the Callback in LinkListFragment. Typically in onListItemClick() we would create an Intent and start a new Activity, but that would lock us into one course of action rather than turn the decision over to the hosting activity to make based on our current environment.

Callbacks Implementation in LinkListActivity

Now in the LinkListActivity hosting activity class we implement the fragment’s Callback Interface and override OnLinkSelected(). We happen to be performing a singular task in the activity onLinkSelected() method, but we could check for the existence of various fragment containers or other conditions for modifying the display of the Link Details screen if we wanted to do so.

Android Coder Notes for this Post

Callbacks were implemented in NixMashupLinks from the initial Version 1.0.1 Branch in the repository.