Django
Django

Reputation: 94

How onAttach() gets to know which activity is calling it (Android Studio)

 @Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try{
        activityCommander = (TopSectionListener) activity;
    }catch (ClassCastException e){
        throw new ClassCastException(activity.toString());
    }
}

I Want to know how an Activity calls onAttach of fragment , so that fragment comes to know by which activity it is called or attached to ?

Upvotes: 1

Views: 723

Answers (1)

Arpit Ratan
Arpit Ratan

Reputation: 3026

Activity doesn't call the onAttach() method, Android framework does. It is called when we commit() a fragment transaction.

When we commit a fragment in an activity using getFragmentManager(), the fragment is attached to lifecycle of that activity. Hence the android framework calls onAttach() event in the fragment. It's kind of hook method which can be overridden to get the call back that fragment is getting attached on an activity.

Upvotes: 4

Related Questions