Java – Is tightly coupled fragment OK in Android (in some cases)?

Is tightly coupled fragment OK in Android (in some cases)?… here is a solution to the problem.

Is tightly coupled fragment OK in Android (in some cases)?

When implementing fragment-to-activity communication, a common example is:

MyActivity extends Activity implements MyInterface {
  ...
  @Override
  public void myMethod() {
   Do something....
  }
  ...
}

MyFragment extends Fragment {
  ...
  private void aMethod() {
    ((MyInterface) getActivity()).myMethod();
  }
  ...
}

The fact is that in my projects, fragments are usually only used to decompose existing activities in different modules in a “divide et impera” way (perhaps refactoring when the activity becomes too complex). It doesn’t make any sense to attach one of these fragments to another activity (different from the activity from which the fragment is extracted).

So in my case, I usually get:

MyActivity extends Activity {
  ...
  void myMethod() {
   Do something....
  }
  ...
}

MyFragment extends Fragment {
  ...
  private void aMethod() {
    ((MyActivity) getActivity()).myMethod();
  }
  ...
}

So the scary question is: if fragments are always used only in that activity, why do we have to use interfaces? Is this bad practice? What are the advantages of using an interface in these situations?

Solution

I don’t think it’s a bad habit. What problem are you trying to solve when you use the interface? You try to anticipate the use of fragments for other activities. If this doesn’t happen, then your interface will only add complexity without any benefit.

Another benefit might be to define which methods of the activity the fragment can call, so your interface is clearly defined. However, the benefits of this are debatable.

Also, I usually group activities and fragments by function in a package. So if I’m writing this code, I’m going to make the myMethod package private, which obviously can’t be done through an interface. So, to some extent, it can even improve the packaging.

Related Problems and Solutions