1

What is the advantage of using an interface to communicate from a fragment to an activity, as described here: http://developer.android.com/training/basics/fragments/communicating.html

This creates an unecessary dependency when we could have created an "onArticleSelected()" method in the activity WITHOUT THE INTERFACE and called it in the fragment via getActivity().onArticleSelected().

What if the activity, at another point in time contain a fragment where there are no articles, why create this illogical dependency and add more code?

Marc
  • 219
  • 1
  • 15

1 Answers1

3

Using an interface actually removes dependency on a specific Activity class. It allows the Fragment to work with any Activity that implements the interface, not just a single Activity.

Dharmik Thakkar
  • 1,650
  • 1
  • 9
  • 18
cybersam
  • 63,203
  • 6
  • 53
  • 76
  • What does the interface have to do with anything? If I want to use the fragment in a different activity, I just have to instantiate it and use it. – Marc Feb 11 '16 at 03:36
  • In the `HeadlinesFragment` example on your linked page, your Fragment would be dependent a specific Activity implementation unless you used an interface. So, you can not just "instantiate it and use it" without an interface. – cybersam Feb 11 '16 at 03:39
  • As @cybersam says, the interface is not really for the activity to talk to the fragment (which is quite easy, you can just use the concrete instance in that case), but for the fragment to be able to talk to the activity, without knowing exactly what particular activity that is. In other words, the activities will be polymorphic to the fragment. – Logain Feb 11 '16 at 03:41
  • but now the activity is coupled to the interface, when we could achieve the same by just having a onArticleSelected() method in the activity. If the activity holds a fragment that needs that, great, call it from the fragment. Otherwise, don't. – Marc Feb 11 '16 at 03:44
  • If you manually create a method in the Activity then doing getActivity().method() should not work. If you somehow have it working then it does not in all cases. In my app it doesn't work that way. – CmosBattery Feb 11 '16 at 03:45
  • @Mark, the problem here is that, for your implementation, the fragment would need to know the exact class of the activity if it needs to communicate with it, and would not be reusable. I understand your concern, and you don't actually need to implement the interface on the Activity if you give a callback to the fragment instead (and then *that* callback would need to implement the interface) – Logain Feb 11 '16 at 03:47
  • Thanks, I see a detailed explanation in a recommended post. it didnt come up in my search. i will delete this question – Marc Feb 11 '16 at 03:51