How to call method in main activity from other activity?

前端 未结 5 1909
清歌不尽
清歌不尽 2020-12-20 07:25

I want to call public method in main activity from other activity. How can I do that?

class MainActivity extends Activity {
    public void myMethod() {}
}

         


        
5条回答
  •  萌比男神i
    2020-12-20 08:07

    How to call method in MainActivity from another activity SOLVED

    Sometimes you cannot make the method static because it depends on all sort of other state in your MainActivity. Making all the depend state also static is tantamount to just making everything global and this is just not a good idea.

    Also there is nothing wrong in wanting to call a non-static method on the MainActivity - it's just like one class calling another.

    Here's what you do:

    Your Application is shared across all your Activities (provided they are all in the same process). This application can be used to store state. Although a sensible idea would be just to store the instances of your activities and let them store their respective states, which is what we're going to do.

    1. create your own Application subclass:

      public class MyApplication extends Application { MainActivity mainActivity; }

    2. Adjust the manifest:

    3. In MainApplication initialise MyApplication.mainActivity

      @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyApplication ma = (MyApplication)getApplication(); ma.mainActivity = this; ...

    4. in OtherActivity retrieve the MainActivity instance.

    private MainActivity mainActivity;

       @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
    
            MyApplication ma = (MyApplication)getApplication();
            mainActivity = ma.mainActivity;
            ...
    
    1. Make use of mainActivity instance to call method:

    mainActivity.someMethodOnMainActivtiy();

提交回复
热议问题