Skip to content

Instantly share code, notes, and snippets.

@subodh-malgonde
Last active December 9, 2015 11:17
Show Gist options
  • Save subodh-malgonde/502cc1477760014aae2d to your computer and use it in GitHub Desktop.
Save subodh-malgonde/502cc1477760014aae2d to your computer and use it in GitHub Desktop.
Illustration of boilerplate introduced by the interface-listener pattern used in Android apps to communication between fragment & activity
public class FragmentA extends Fragment{
OnFragmentInteractionListener listener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
public interface OnFragmentInteractionListener{
void foo();
void bar();
}
/*
* Calls to interface methods could involve not null checks as all the
* possible containing activities may not implement the interface
*/
if(listener != null){
listener.foo();
}
}
public class ActivityA extends Activity implements FragmentA.OnFragmentInteractionListener,
FragmentB.OnFragmentInteractionListener,
FragmentC.OnFragmentInteractionListener,
FragmentD.OnFragmentInteractionListener
....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment