Calling Activity Method From Inside A Fragment

Android Learner picture Android Learner · Nov 1, 2013 · Viewed 47.5k times · Source

I am trying to call a method in an activty from a Fragment screen.

I have a method called myMethod() which is in an activity called MyActivity; I have a fragment called Screen1Fragment.

I would like to call MyActivity.myMethod() from inside the Screen1Fragment but I am not sure how to do this.

Previously the Screen1Fragment was an activity and so I was extending MyActivity so that I could directly call myMethod(). But I have had to change the activity to a fragment for sliding tabs usage.

Thanks in advance.

Answer

Sipka picture Sipka · Nov 1, 2013

Use getActivity() in your fragment.

MyActivity activity = (MyActivity) getActivity();
activity.myMethod();

if you are not sure if your fragment is attached to MyActivity then

 Activity activity = getActivity();
 if(activity instanceof MyActivity){
      MyActivity myactivity = (MyActivity) activity;
      myactivity.myMethod();
 }