如何从其他活动中调用主要活动中的方法? [英] How to call method in main activity from other activity?

查看:124
本文介绍了如何从其他活动中调用主要活动中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从其他活动中调用主要活动中的公共方法。我该怎么做?

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?
    }
}


推荐答案

它取决于。


  1. 如果您只想使用某些共享功能(例如执行某些计算的代码)。

  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.

如果你想调用MainActivity,那么MainActivity使用MainActivity UI做了一些事情,你将不得不使用Intent( http://developer.android.com/reference/android/content/Intent.html ),因为MainActivity应该首先恢复,并且只有在此之后才可以使用UI执行某些操作。

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.

在这种情况下,您可能需要为intent添加一些额外的额外内容,这些内容将由MainActivity代码(在onCreate或onResume中)解析并调用适当的方法。

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.

这篇关于如何从其他活动中调用主要活动中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆