onSaveInstanceState不起作用

时间:2016-05-13 20:27:11

标签: android android-activity

当屏幕旋转时......吐司什么都没打印!

public class MainActivity extends AppCompatActivity {

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

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    String a  = savedInstanceState.getString("hello");
    Toast.makeText(MainActivity.this, a, Toast.LENGTH_SHORT).show();

}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    String a = "WTF";
    outState.putString("hello",a);
}

}

我很好地宣告了一切,在这个简单的代码中哪些是无聊的!

2 个答案:

答案 0 :(得分:11)

我认为自从Android操作系统团队超载onSaveInstanceState()方法以来,你已陷入许多开发人员的常见陷阱。

您正在覆盖错误的方法。你想要的是:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    String a = "WTF";
    outState.putString("hello",a);
}

我个人认为,每当Android开发者犯这个错误时,我认为Craig Mautner应该被迫捐款 - source

答案 1 :(得分:0)

同样的问题 试试改成这个

    @Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    String a = "WTF";
    outState.putString("hello",a);
}