2016-05-13 56 views
5

當屏幕旋轉時... Toast打印什麼都沒有!onSaveInstanceState不起作用

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

}

我宣佈一切都很好,,哪裏是在這個簡單的代碼中的無賴!?

回答

10

我認爲自從Android操作系統團隊重載onSaveInstanceState()方法以來,您已經陷入了許多開發者的共同陷阱。您正在重寫錯誤的方法。你想要的是:

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

我個人認爲,克雷格Mautner應該被強迫每一個Android開發人員,使這個錯誤的時間捐錢 - source