简体   繁体   English

onSaveInstanceState在onCreate之后不可变

[英]onSaveInstanceState not getting variable after onCreate

Hi can someone explain me please what I am doing wrong because I cannot get a variable from savedInstanceState, int "score" every time I change my screen orientation it resets the variable. 您好,有人可以向我解释我在做什么错,因为每次我更改屏幕方向时,都无法从saveInstanceState获取一个变量,即int“ score”,它将重置该变量。

int score;
EditText et;
String etString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et = (EditText) findViewById(R.id.editText);
    if (savedInstanceState != null) {
        score = savedInstanceState.getInt("score");
        et.setText(savedInstanceState.getString("etText"));
        Log.d("TEST2", "score " + score);
    } else {
        score = 0;
    }

}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);

    etString = et.getText().toString();
    outState.putString("etText", etString);
    outState.putInt("score", score);
    Log.d("TEST", "score " + score);
}

public void performAction(View v) {
    switch (v.getId()) {
    case R.id.button:
        score += 1;
        break;
    case R.id.button2:
        Toast.makeText(getApplicationContext(), "Score: " + score, Toast.LENGTH_LONG).show();
        break;
    }

}

Please help if you know the solution. 如果您知道解决方案,请提供帮助。

you're using a method that is from Lollipop, change to the version that is available since Android 1.0 您使用的是Lollipop中的方法,请更改为自Android 1.0起可用的版本

@Override
public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

see the different method signature? 看到不同的方法签名?

You should implement onRestoreInstanceState instead of getting value in onCreate . 您应该实现onRestoreInstanceState而不是在onCreate中获取价值。 The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null. 仅当存在要还原的保存状态时,系统才调用onRestoreInstanceState(),因此您无需检查Bundle是否为null。

public class OrientationChangeActivity extends Activity {

private EditText edtUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edtUser = (EditText) findViewById(R.id.edtUsername);



    if (savedInstanceState != null /*&& savedInstanceState.getString("edt") != null*/) {
        edtUser.setText(savedInstanceState.getString("edt"));
        Log.e("Demo","==================================="+savedInstanceState.getString("edt"));
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("edt", edtUser.getText().toString());
    super.onSaveInstanceState(outState);
}

} }

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

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