4

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.

Umair
6,42616 gold badges45 silver badges50 bronze badges
asked Dec 20, 2017 at 7:05
1

4 Answers 4

4

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 Dec 20, 2017 at 7:13
Sign up to request clarification or add additional context in comments.

so for each fragment, you would only have one Listener(interface), correct?
Yes, there will only be one interface which will be used to communicate with the activity, who is hosting the fragment.
But, it is not mandatory to only have one interface, you can have hundreds of them too. But, why create 100s when that work can be done with only one interface.
1

Here is an example of Fragment to Activity communication:

public class HeadlinesFragment extends ListFragment {
 OnHeadlineSelectedListener mCallback;
 // Container Activity must implement this interface
 public interface OnHeadlineSelectedListener {
 public void onArticleSelected(int position);
 }
 @Override
 public void onAttach(Activity activity) {
 super.onAttach(activity);
 // This makes sure that the container activity has implemented
 // the callback interface. If not, it throws an exception
 try {
 mCallback = (OnHeadlineSelectedListener) activity;
 } catch (ClassCastException e) {
 throw new ClassCastException(activity.toString()
 + " must implement OnHeadlineSelectedListener");
 }
 }
 ...
}

Now the fragment can deliver messages and commuticate to the activity by calling the onArticleSelected() method (or other methods in the interface) using the mCallback instance of the OnHeadlineSelectedListener interface. So basically it's for callbacks

answered Dec 20, 2017 at 7:15

1

The purpose of using the onAttach with the following code:

public void onAttach(Context context) {
 super.onAttach(context);
 try{
 activityCommander = (exampleFragmentListener)context;
 }catch(Exception e){
 throw new ClassCastException(context.toString());
 }
}

simply is to make a dead contract of Activity and Fragment. Whenever the contract is not obeyed by the Activity, both the Activity and Fragment will be dead. Both of them will die by throwing the exception.

For onAttach details, please read my previous answer: What if onAttach() is not overridden inside the fragment code?

answered Dec 20, 2017 at 8:39

Comments

0

Add This on your Fragemnt

Activity activity;
@Override
public void onAttach(@NonNull Context context) {
 super.onAttach(context);
 activity = context instanceof Activity ? (Activity) context : null;
}

Then change getContext() , getActivity() , requireActivity() or requireContext() with activity

answered Aug 27, 2022 at 11:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.