Call parent's activity from a fragment

40,853

Solution 1

Yes, Its right by calling getActivity and cast it with parent activity to access its methods or variables ((ParentActivityName)getActivity())

Try this one.

ParentActivityName is parent class name

Solution 2

2021 UPDATE

As it's told in the comments, Fragment#onAttach(Activity) is deprecated starting from API 23. Instead:

@Override
public void onAttach(Context ctx) {
    super.onAttach(ctx);
    
    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        // Only attach if the caller context is actually an Activity
        if (ctx instanceof Activity) {
          mCallback = (OnHeadlineSelectedListener) ctx;
        }
    } catch (ClassCastException e) {
          throw new ClassCastException(ctx.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

ORIGINAL ANSWER

The most proper way is to make your Activity implement an Interface and use listeners. That way the Fragment isn't tied to any specific Activity keeping it reusable. Into the Fragment:

@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");
    }
}

That way, you make the Activity listen to the fragment when it's attached to it.

See also:

Share:
40,853
user1746708
Author by

user1746708

Updated on July 09, 2022

Comments

  • user1746708
    user1746708 almost 2 years

    If I'm inside a Fragment how can I call a parent's activity?