4

I do not understand something. Now, I am reading the documents in android developer site and there, it is written that in order to communicate with fragments, I should implement interface. However, now I can easily access the widgets, exist on fragment, in Main activitiy class.

For example, in main activity class, by issuing following line, I can access fragment´s TextView.

TextView t1 = (TextView) findViewById(R.id.t1);

In this condition, why do i need to implement interface? (forgive my ignorance and thanks)

Ken Vors
  • 197
  • 1
  • 3
  • 14
  • There are plenty of code examples here: http://stackoverflow.com/questions/12142255/call-activity-method-from-adapter. These show how to use an interface for `Activity` to `Adapter`, the same way you would use an `Interface`. – Jared Burrows Apr 11 '15 at 21:31
  • possible duplicate of [Fragment-Fragment communication in Android](http://stackoverflow.com/questions/15447804/fragment-fragment-communication-in-android) – Jared Burrows Apr 11 '15 at 21:32

1 Answers1

4

On Fragment, how do you access a method of the Activity it is attached to? You could call getActivity() but that will only give access to the methods available to the parent Activity object, not your implementation of it with your own custom methods.

To access those custom methods, you need to tell Java that you know that the particular Activity you want to get is the one you created, lets call it MyActivity, which obviously extends Activity or some other implementation of it like ActionBarActivity. In this case you can call ((MyActivity)getActivity()).myMethod();

The problem now is that you are coupling your fragment to that particular activity. By doing so, you won't be able to use your fragment with any other activity in your project because that particular fragment will be looking for MyActivity.

So instead, you declare myMethod() in an interface and make your Activity implement it. If in the future you need to use the fragment with another Activity, all you have to do is make it implement the interface as well.

Ricardo
  • 7,785
  • 8
  • 40
  • 60