Calling Activity Method From Inside A Fragment [duplicate]

£可爱£侵袭症+ 提交于 2019-12-03 07:10:18

问题


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.


回答1:


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();
 }



回答2:


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.




回答3:


If the method is the static method of MainActivity, something like:

    public static void someMethod(){}

Then, it is pretty straightforward. Just call

   MainActivity.someMethod()

However, I guess what you really want is to access some function from the Activity class. Then you can use the following code in the Fragment view creater

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState){

        container.getContext().someMethod();

   }


来源:https://stackoverflow.com/questions/19726697/calling-activity-method-from-inside-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!