Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // How can I call myMethod() in MainActivity?
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
615 views
Welcome To Ask or Share your Answers For Others

1 Answer

It depends.

  1. In the case if you want just to use some shared functionality (as example the code which does some calculation).

    I would recommend to move this shared functionality to some standalone class and call it from there.

  2. In the case if you want to call MainActivity, so MainActivity did something with MainActivity UI, you will have to use Intent (http://developer.android.com/reference/android/content/Intent.html), because MainActivity should be resumed first and only after this it can do something with UI.

    In this case, you may need to add some additional extra's to intent, which will be parsed by MainActivity code (in onCreate or onResume) and call appropriate method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...