In your Fragment
class, have a TAG
field. Naming a fragment Fragment
can be a bit confusing as it is the same name as an Android Fragment
, so I will use ExampleFragment
:
public class ExampleFragment extends android.support.v4.app.Fragment implements FragmentCommunicator {
public static final String TAG = "ExampleFragment";
// ...
}
Now, when you replace the fragment in the activity, make sure to pass the TAG
:
getSupportFragmentManager().beginTransaction().replace(R.id.container ,fragment, ExampleFragment.TAG).commit();
Note that in your case it would be Fragment.TAG
, but I used ExampleFragment
to clarify that Fragment.TAG
is not part of the Android SDK.
To get a reference of your fragment in your activity, use the FragmentManager
to find your fragment:
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(ExampleFragment.TAG);
You can then make sure that myFragment
is not null
and cast it to FragmentCommunicator
:
if (myFragment != null) {
fragmentCommunicator = (FragmentCommunicator) myFragment;
}
Note that in your example fragmentCommunicator = (FragmentCommunicator) getApplication();
is invalid because it is your fragment that is implementing the interface, not your application.