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

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

java - How to call method in main activity from other activity?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...