在主要活动中的3个活动中传递价值

时间:2019-04-14 03:24:30

标签: android

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

3 个答案:

答案 0 :(得分:0)

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

Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("EXTRA_SESSION_ID", variable); 
startActivity(intent);

访问下一个活动的意图

String variable= getIntent().getStringExtra("EXTRA_SESSION_ID");

Intents文档具有更多信息(请参阅标题为“其他”的部分)。

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

答案 1 :(得分:0)

您可以创建一个Util Class,在其中Class创建一个名为static的{​​{1}}变量。

根据按下的difficulty进行分配。

Button内部分配它,以后再获取它。

谢谢。

答案 2 :(得分:0)

设置“首选项”中的值:

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.