Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在主活动的3个活动中传递值_Android - Fatal编程技术网

Android 在主活动的3个活动中传递值

Android 在主活动的3个活动中传递值,android,Android,我在主活动中有3个按钮,这3个按钮打开另一个活动,它是简单、中等和困难的游戏类型。我想得到每个难度等级的分数,并将其存储在主要活动中,有没有这个例子?任何帮助都将不胜感激,谢谢 最简单的方法是将您要共享的变量传递给主活动,以用于启动活动: Intent intent = new Intent(getBaseContext(), MainActivity.class); intent.putExtra("EXTRA_SESSION_ID", variable); startActivity(in

我在主活动中有3个按钮,这3个按钮打开另一个活动,它是简单、中等和困难的游戏类型。我想得到每个难度等级的分数,并将其存储在主要活动中,有没有这个例子?任何帮助都将不胜感激,谢谢

最简单的方法是将您要共享的变量传递给主活动,以用于启动活动:

Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("EXTRA_SESSION_ID", variable); 
startActivity(intent);
在下一个活动中访问该意图

String variable= getIntent().getStringExtra("EXTRA_SESSION_ID");
意向文件中有更多信息,请查看标题为Extras的部分

您可以将变量存储到MainActivity中所需的任何变量中并使用它。

您可以创建一个Util类,在该类中创建一个名为“难度”的静态变量

根据按下的按钮分配

在OnClickListener中分配它,稍后检索它


谢谢。

设置首选值:

SharedPreferences.Editor editor = getSharedPreferences("MyPref", 
MODE_PRIVATE).edit();
 editor.putInt("begginer", 120);  // put begginer level score here
 editor.putInt("medium", 37);  // put the medium level score here
 editor.putInt("hard", 12);  // put hard level score here
 editor.apply();
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE); 
  int begginer_score = prefs.getInt("begginer", 0); //0 is the default value.
  int medium_score = prefs.getInt("medium", 0); //0 is the default value.
  int hard_score = prefs.getInt("hard", 0); //0 is the default value.
要从首选项检索数据,请执行以下操作:

SharedPreferences.Editor editor = getSharedPreferences("MyPref", 
MODE_PRIVATE).edit();
 editor.putInt("begginer", 120);  // put begginer level score here
 editor.putInt("medium", 37);  // put the medium level score here
 editor.putInt("hard", 12);  // put hard level score here
 editor.apply();
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE); 
  int begginer_score = prefs.getInt("begginer", 0); //0 is the default value.
  int medium_score = prefs.getInt("medium", 0); //0 is the default value.
  int hard_score = prefs.getInt("hard", 0); //0 is the default value.

如果有用的话。请勾选您选择的答案。您也可以交替使用SharedReferences。有关如何使用SharedReference的详细信息,请参见我的答案