Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Activity Method From Inside A Fragment [duplicate]

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.

like image 600
Android Learner Avatar asked Nov 01 '13 12:11

Android Learner


2 Answers

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();
 }
like image 145
Sipka Avatar answered Nov 08 '22 07:11

Sipka


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

  • implement MyFragmentCallback in the class definition.
  • implement 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.

like image 28
znat Avatar answered Nov 08 '22 09:11

znat