36

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

GOLDEE
  • 2,318
  • 3
  • 25
  • 49
user1746708
  • 691
  • 1
  • 8
  • 16

3 Answers3

85

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

Slim
  • 1,708
  • 5
  • 37
  • 60
DcodeChef
  • 1,550
  • 13
  • 17
  • What if we don't know the name? Example: i am making sdk and it has all fragments in it. I cant ask the sdk user to rename his/her activity. So how to get reference without knowing the name? – Karan Apr 05 '15 at 07:18
  • How would you like to use that reference? – DcodeChef Apr 06 '15 at 07:17
  • 1
    I got it. My use case was to make n fragments in a library and provide to Merchants. I would not know which Activity they would be using the fragments in. It seems making an interface, overriding it in activity and getting a callback from activity seems to be the best practice and in my scenario very helpful.. – Karan Apr 06 '15 at 07:37
  • @kay Cool, that's the way! – DcodeChef Apr 06 '15 at 09:50
  • 1
    Does it has potential for memory leaks? even though I don't store any reference to the parent `Activity`? – Eido95 Jun 11 '18 at 06:00
17

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:

Aritz
  • 30,971
  • 16
  • 136
  • 217
1

Simply call your parent activity using getActivity() method.

CardView cardView = (CardView) getActivity().findView(R.id.your_view);
Chanaka Fernando
  • 2,176
  • 19
  • 19