这是我的GamePlay活动代码
public class GamePlay extends Activity implements OnClickListener {
private boolean disableSound = false;
//.....
//Code Code
//.....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.....
//Code Code
//.....
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("disableSound", disableSound);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
disableSound = savedInstanceState.getBoolean("disableSound");
Menu menu = (Menu)findViewById(R.menu.tic_tac_toe);
MenuItem toggleSoundItemMenu = menu.findItem(R.id.toogle_sound_menu);
if(disableSound)
toggleSoundItemMenu.setTitle(R.string.toggle_sound_off_label);
else
toggleSoundItemMenu.setTitle(R.string.toggle_sound_on_label);
}
//other functions and code
}
现在游戏重启我正在重启活动。以下代码位于onClickListener()内,并带有适当的大小写
case R.id.game_play_restart_button:
Intent restartActivity = new Intent(this,GamePlay.class);
finish();
startActivity(restartActivity);
break;
但是国家仍然没有坚持下去。我禁用声音并重新启动游戏,然后声音重新开启,这是默认行为。我错过了什么?任何建议都表示赞赏。
答案 0 :(得分:1)
只要活动尚未被系统销毁,系统就会保留savedInstanceState包。 当您调用完成时,您将销毁当前活动以及随附的捆绑包。 这就是你无法获得布尔值的原因。
你应该考虑在意图中将此布尔值作为额外内容传递:
restartActivity.putExtra("disableSound", disableSound)
然后是你活动的onCreate:
getIntent().getBooleanExtra("disableSound", false)
请注意,最后一个参数false只是一个默认值。如果这是您想要的行为,您可以将其设置为true。