1
我有兩個佈局(肖像和風景)的應用程序。有4個我想要保存的int值,因此它們在旋轉時不會被擦除。爲此,我呼籲拯救實例,然後我恢復在onCreate方法的狀態是這樣的:onsaveinstancestate只能工作一次?
private int operando1;
private int operando2;
private int operador;
private int contadorIntentos;
private String operadorTxt;
private static final String CONTADOR_INTENTOS = "contadorIntentos";
private static final String OPERANDO1 = "operando1";
private static final String OPERANDO2 = "operando2";
private static final String OPERADOR = "contadorIntentos";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CONTADOR_INTENTOS, contadorIntentos);
outState.putInt(OPERANDO1, operando1);
outState.putInt(OPERANDO2, operando2);
outState.putInt(OPERADOR, operador);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_principal);
//other random code
Random generador = new java.util.Random();
if (savedInstanceState != null){
contadorIntentos = savedInstanceState.getInt(CONTADOR_INTENTOS);
operando1 = savedInstanceState.getInt(OPERANDO1);
operando2 = savedInstanceState.getInt(OPERANDO2);
operador = savedInstanceState.getInt(OPERADOR);
}else {
contadorIntentos = 0;
operando1 = generador.nextInt(1000);
operando2 = generador.nextInt(1000);
operador = generador.nextInt(4);
}
嗯,事實證明,它不僅節省了狀態一次。第一次旋轉後(當它保存正確)後,如果我修改的東西,並再次旋轉它恢復第一次旋轉的狀態。這就像onsaveinstancestate只能使用一次。爲什麼?
是的,那是預期的行爲。它應該只在第一次生成數字,而下一個應該使用已經生成的數字。相反,第一次它會生成數字,第二次使用已保存的數字,但如果計數器上升(在未包含的代碼中),則不會記錄該更改。 – kace91 2014-11-01 18:59:37
無論你在'//其他隨機代碼中做什麼,你都會用savedInstanceStateFields覆蓋它。我建議在恢復狀態後放置'// other randomCode'。這是你做事的順序問題。 – akodiakson 2014-11-01 19:03:36
我想要保存的修改不會發生在其他隨機代碼中,而是出現在oncreate()方法中的按鈕中。 – kace91 2014-11-01 19:07:43