Android Fragment OnAttach method

Issue

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.

Solution

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.

Answered By – Saran Sankaran

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published