2015-09-13 101 views
0

我正在制作一个允许用户选择不同类型的游戏,在MainActivity中将有一个警报对话框供用户选择。 有2个元素(speed_1和speed_2)是影响GameActivity中难度的数字将数据更改为其他活动

我想让用户在Alert对话框中选中“Easy”,speed_1和speed_2将变为1(在GameActivity)

如果在警告对话框中,用户检入 “困难”,speed_1和speed_2将更改为3(在GameActivity)

谢谢!

void generateLevelListDialog() { 
    // Instantiate an AlertDialog.Builder with its constructor 
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 

    // Specify the list in the dialog using the array 
    builder.setTitle("Difficulty").setItems(R.array.levels_array, 
      new DialogInterface.OnClickListener() { 
       // Chain together various setter methods to set the list 
       // items 
       // The index of the item selected is passed by the parameter 
       // which 
       public void onClick(DialogInterface dialog, int which) { 
        //switch to game activity 
        Intent gameIntent = new Intent(MainActivity.this, GameActivity.class); 
        //change ball speed and racket length 
        switch (which) { 
         case 0: 

          break; 

         case 1: 
          break; 

         case 2: 
          break; 

         default: 
          break; 
        } 
        //start activity 
        startActivity(gameIntent); 

       } 
      }); 
    //create and show list dialog 
    AlertDialog dialog = builder.create(); 
    dialog.show(); 
} 

回答

0

一般来说,你这里有两种选择:

1)选择的值保存到喜好,并在GameActivity日后读取:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

写在MainActivity

preferences.edit().putInt("speed_1", speed_1).apply(); 

GameActivity中阅读

int speed_1 = preferences.getInt("speed_1", 0); 

作为用户下次玩游戏时的奖励,它将使用先前选择的难度级别。

2)通难度值(speed_1..speed_3)到GameActivity通过gameIntent使用演员:

写在MainActivity

Intent gameIntent = new Intent(MainActivity.this, GameActivity.class); 
gameIntent.putExtra("speed_1", speed_1); 

GameActivity

Bundle extras = getIntent().getExtras(); 
String speed_1 = extras.getInt("speed_1"); 
+0

谢谢您的回复,当运行应用程序时没有错误,但在该应用程序中,当我小鸡“轻松”时,游戏发生冲突,您有任何建议吗? – aaaabbbb

+0

检查你的IDE中的logcat /输出窗口,它应该显示一个异常堆栈跟踪,它会给你一个线索。 – Mikhail

0

你可以阅读像下面那样用Intent传递值

int level; 

Intent intent = new Intent(MainActivity.this, GameActivity.class); 
      switch (which) { 
        case 0: 
         level = 1; 
         break; 
        case 1: 
         level = 2; 
         break; 
        case 2: 
         level = 3; 
         break; 
        default: 
         level = 1;  // Default Value 
         break; 
       } 

intent.putExtra("DIFFICULTY_LEVEL", level); 
startActivity(intent); 

而且在GameActivity.java,你可以简单地获得价值像下面

int level = getIntent().getIntExtra()("DIFFICULTY_LEVEL", 1); // where '1' is default value 

谢谢!

+0

非常感谢您的回复,我正在尝试将其应用于我的代码,但om游戏活动“()(”DIFFICULTY_LEVEL“,1);”红色下划线,它说“例外令牌”,我该怎么办?谢谢 – aaaabbbb

+0

这个问题解决了,但是运行应用程序时没有错误,但是在那个应用程序中,当我小鸡“轻松”的时候,游戏冲突了,你有什么建议吗? – aaaabbbb

+0

您将从您面临的Logcat发布异常/错误将会很有帮助。 – Omar