Call Activity Method From Fragment

后端 未结 5 943
南笙
南笙 2021-01-14 10:12

I\'m dealing with fragments.
I have an Activity and different fragments.
Each fragment need the access to a Class(call i

5条回答
  •  野的像风
    2021-01-14 10:48

    Define an interface called Callbacks (or something else if you want). In it, have a public method called getClassX(). Then make your Activity implement the Callbacks interface.

    In your Fragments, in onAttach, store a reference to a Callbacks object (i.e. your activity via something like:

    if(activity instanceof Callbacks)
        mCallbacks = (Callbacks)activity;
    

    This will guarantee that the Fragments are able to call the function. (in case you want to reuse the fragments later in another app)

    Then in your Activity, in onCreate(), create an instance of ClassX. In your getClassX() method, just return a reference to it.

    When you want a reference to it from your Fragments, call mCallbacks.getClassX() and you should be sorted.

提交回复
热议问题