且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从其他活动中调用主要活动中的方法?

更新时间:2022-12-19 13:53:35

它取决于。


  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.