我制作的游戏将允许用户选择不同的类型,在MainActivity中将有一个警报对话框供用户选择。 有2个元素(speed_1和speed_2)是影响GameActivity难度的数字
我希望如果用户检查" 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 :(得分: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)使用附加内容通过GameActivity
将难度等级值(speed_1..speed_3)传递给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");
答案 1 :(得分: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
谢谢!