![](/img/trans.png)
[英]Using onCreate Bundle savedInstanceState with wallpaper service? (Watchface)
[英]Where is Bundle object created in onCreate(Bundle savedInstanceState)
在Android中, onCreate
方法將savedInstanceState
作為Bundle對象的引用。 我只想知道在何處以及如何創建Bundle
對象?
如果您將應用程序的狀態保存在捆綁包中(通常在onSaveInstanceState中為非持久性動態數據),那么如果需要重新創建活動(例如,方向更改),則可以將其傳遞回onCreate,以免丟失此先驗信息。 如果未提供任何數據,則saveInstanceState為null。
您需要重寫onSaveInstanceState(Bundle savedInstanceState),並將要更改的應用程序狀態值寫入Bundle參數,如下所示:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}
Bundle本質上是一種存儲NVP(“名稱-值對”)映射的方法,它將被傳遞給onCreate()以及onRestoreInstanceState(),您可以在其中提取如下值:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.