Nested fragmented-fragmented interactions with Android

Android's best practices for fragment-fragment interaction (described here and here ) forces Activity implement a listener defined by a child fragment. Activity then manages the relationship between the fragments.

In my opinion, this means that the fragments are loosely coupled to each other. Nonetheless,

  • Is this also the case for nested fragments? I can imagine that for a nested fragment, it might make sense to tell the parent fragment directly to it instead of Activity.

  • If the nested fragment has its own parent fragment, its listener implements it, as if one (or should one) require the parent fragment from it. In other words, it seems like a paradigm for the following, but for Fragments :

     @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } 
+5
source share
3 answers

As long as you define an interface in a fragment, you can implement parent activity or parent fragment. There is no rule that a fragment should not implement the interface of a child fragment. One example, when that makes sense, is that fragment A has two children. Fragments B, C. A implements interface B, when A receives a callback, it may need to update fragment C. Exactly the same with activity, only at a different level.

+1
source

If someone needs an example implementation that provides a parent context, implements callbacks without worrying about whether this is an activity or a fragment, the following worked for me:

 @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof Callbacks) { mCallbacks = (Callbacks) context; } else { if (getParentFragment() != null && getParentFragment() instanceof Callbacks) { mCallbacks = (Callbacks) getParentFragment(); } else { throw new RuntimeException(context.toString() + " must implement " + TAG + ".Callbacks"); } } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } 

Enjoy it!

+4
source

You can implement the same template for interaction between parents and parents using getParentFragment () . A parent fragment refers to any fragment that is added through its ChildFragmentManager. If this fragment is bound directly to Activity, this method returns null.

0
source

Source: https://habr.com/ru/post/1201369/


All Articles