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.
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();
}
You should make your fragment totally independant of the activity you are attaching it to. The point of Fragments is that you can re-use them in different contexts with different activities. To achieve that and still being able to call methods from your Activity the following pattern in recommended in the official documentation.
In your fragment:
define a public interface with the method
public interface MyFragmentCallback{
public void theMethod();
}
define a field and get a cast reference:
private MyFragmentCallback callback;
public void onAttach(Activity activity){
callback = (MyFragmentCallback) activity
super.onAttach(activity);
}
In your Activity
MyFragmentCallback
in the class definition.theMethod()
in your activity (Eclipse will ask you to do so)Then, from your fragment, you can call callBack.theMethod()
The difference between this and simply calling your method on getActivity() is that your fragment is not paired with this specific activity anymore. So you may re-use it with other activity for example one for phones and the other for tablets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With