简体   繁体   English

onsaveinstancestate仅工作一次?

[英]onsaveinstancestate only works once?

I have an app with two layouts (portrait and landscape). 我有一个具有两种布局(纵向和横向)的应用程序。 There are 4 int values I want to save so they don't get erased on rotation. 我要保存4个int值,这样它们就不会在旋转时被擦除。 For that, I call on save instance and then I recover the state on the onCreate method like this: 为此,我调用了save实例,然后像下面这样在onCreate方法上恢复状态:

 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);
        }

Well, it turns out that it only saves the state once. 好吧,事实证明它只保存一次状态。 after the first rotation (when it saves correctly) if I modify things and rotate again it recovers the state of the first rotation. 第一次旋转后(正确保存时),如果我修改并再次旋转,它将恢复第一次旋转的状态。 It's like onsaveinstancestate only works once. 就像onsaveinstancestate只能运行一次。 Why? 为什么?

因为saveInstanceState在随后的所有循环中都不为空,所以您永远不会生成新的数字(例如:再也不会调用此数字: operando1 = generador.nextInt(1000) ...等...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM