Last active
December 9, 2015 11:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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