java 来自另一个活动的 Android 调用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4434179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android call method from another activity
提问by semajhan
How would I call a method from a different activity? In my main activity, I have a button that shows a dialog to set the difficulty level of the game. Then you click start game which starts a new activity containing a view with all the game information. I need to send the difficulty level chosen to the other activity but cannot seem to figure out how to.
我将如何从不同的活动调用方法?在我的主要活动中,我有一个按钮,显示一个对话框来设置游戏的难度级别。然后单击开始游戏,这将启动一个包含所有游戏信息视图的新活动。我需要将选择的难度级别发送到其他活动,但似乎无法弄清楚如何去做。
回答by ninjasense
You could put it in the extras with the intent:
你可以把它放在额外的地方:
Intent StartGame = new Intent(this, StartGame.class);
StartGame.putExtra("difficulty", difficultyLevel);
startActivity(StartGame);
Then in your StartGame.class you can retrive it like this(assuming its a string):
然后在您的 StartGame.class 中,您可以像这样检索它(假设它是一个字符串):
Bundle extras = getIntent().getExtras();
if (extras != null) {
String difficulty= extras.getString("difficulty");
}
回答by RodJ
Well I don't know how sound my solution is but I created a myApplication class which sub classes the Application class .
好吧,我不知道我的解决方案有多健全,但我创建了一个 myApplication 类,它对 Application 类进行了子类。
This holds the reference to the activity I wanted to call
这包含对我想调用的活动的引用
import android.app.Application;
public class myApplication extends Application {
public PostAndViewActivity pv;
}
When the PostAndViewActivity calls the oncreate is sets the pv to point to itself.
当 PostAndViewActivity 调用 oncreate 时,将 pv 设置为指向自身。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((myApplication) getApplication()).pv = this;
Then when I want to call the method I want I just use code like this:
然后当我想调用我想要的方法时,我只使用这样的代码:
((myApplication) getApplication()).pv.refreshYourself();
Perhaps a bit hacky but it works..... I welcome some critisism for this ;-)
也许有点hacky但它有效.....我欢迎对此进行一些批评;-)