Communicating between a fragment and an activity - best practices Communicating between a fragment and an activity - best practices android android

Communicating between a fragment and an activity - best practices


The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

Once it has implemented that interface, you could do anything you want in the method it overrides.

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.

There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.

I hope this was helpful to you!


The suggested method for communicating between fragments is to use callbacks\listeners that are managed by your main Activity.

I think the code on this page is pretty clear:http://developer.android.com/training/basics/fragments/communicating.html

You can also reference the IO 2012 Schedule app, which is designed to be a de-facto reference app. It can be found here:http://code.google.com/p/iosched/

Also, here is a SO question with good info:How to pass data between fragments


It is implemented by a Callback interface:

First of all, we have to make an interface:

public interface UpdateFrag {     void updatefrag();}

In the Activity do the following code:

UpdateFrag updatfrag ;public void updateApi(UpdateFrag listener) {        updatfrag = listener;}

from the event from where the callback has to fire in the Activity:

updatfrag.updatefrag();

In the Fragment implement the interface in CreateView do the following code:

 ((Home)getActivity()).updateApi(new UpdateFrag() {        @Override        public void updatefrag() {              .....your stuff......        } });