Skip to content
Advertisement

Android Fragment OnAttach method

I’m new to Android development and have a question about OnAttach(Context context) method. As far as I understand you override OnAttach method in the class that you extend Fragment and what it basically does is it attaches the fragment to the Activity(Context) that gets passed as a parameter. However, in a lot of example codes I’ve seen on the internet, people create an interface with methods that the main Activity needs to implement and in OnAttach method, they typecast context as the interface for ex)

public class exampleFragment extends Fragment{

exampleFragmentListener activityCommander;

public interface exampleFragmentListener{
    public void someMethod(String top, String bot);

}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        activityCommander = (exampleFragmentListener)context;

    }catch(Exception e){
        throw new ClassCastException(context.toString());

    }
}

What I don’t get is this piece of code :

activityCommander = (exampleFragmentListener)context;

What’s the purpose of typecasting context as exampleFragmentListener? Why would we typecast our main activity to fragment? Why can’t the main activity just implement the interface/implement interface methods? Thank you in advance.

Advertisement

Answer

When we want a fragment to communicate with an Activity we use a interface. Now suppose if there are 2 Activities which host the same Fragment, and at runtime we don’t know from which activity is the fragment is currently. That is the reason we use onAttach(). The Context provided to us in the parameter is the context of the Activity which is hosting it. So once we have the casted instance, we can use that to communicate with the activity.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement