来自其他活动的Android通话方法

sem*_*han 1 java android

我如何从不同的活动中调用方法?在我的主要活动中,我有一个按钮,显示一个对话框来设置游戏的难度级别.然后单击开始游戏,开始一个包含所有游戏信息视图的新活动.我需要将选择的难度级别发送到其他活动,但似乎无法弄清楚如何.

nin*_*nse 6

你可以把它放在额外的意图:

Intent StartGame = new Intent(this, StartGame.class);
StartGame.putExtra("difficulty", difficultyLevel);
startActivity(StartGame);
Run Code Online (Sandbox Code Playgroud)

然后在你的StartGame.class中你可以像这样(它假设它是一个字符串)来检索它:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String difficulty= extras.getString("difficulty");
}
Run Code Online (Sandbox Code Playgroud)


小智 6

好吧,我不知道我的解决方案有多健全,但我创建了一个myApplication类,它为Application类提供子类.

这包含了我想要调用的活动的引用

import android.app.Application;

public class myApplication extends Application {
    public PostAndViewActivity pv;
}
Run Code Online (Sandbox Code Playgroud)

当PostAndViewActivity调用oncreate时,将pv设置为指向自身.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ((myApplication) getApplication()).pv = this;
Run Code Online (Sandbox Code Playgroud)

然后,当我想调用我想要的方法时,我只使用这样的代码:

((myApplication) getApplication()).pv.refreshYourself();
Run Code Online (Sandbox Code Playgroud)

也许有点hacky但它​​的确有效.....我欢迎对此有一些批评;-)