[英]Android call method from another activity
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.
我需要将选择的难度级别发送给其他活动,但是似乎无法弄清楚该怎么做。
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");
}
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,但是它可以工作.....我对此表示欢迎;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.