不需要再手寫 onSaveInstanceState 了,因為你的時間非常值錢
如果你是一個有經驗的 Android 程式設計師,那麼你肯定手寫過許多 onSaveInstanceState
以及 onRestoreInstanceState
方法用來保持 Activity 的狀態,因為 Activity 在變為不可見以後,系統隨時可能把它回收用來釋放記憶體。重寫 Activity 中的 onSaveInstanceState
方法 是 Google 推薦的用來保持 Activity 狀態的做法。
Google 推薦的最佳實踐
onSaveInstanceState
方法會提供給我們一個 Bundle
物件用來儲存我們想儲存的值,但是 Bundle
儲存是基於 key - value 這樣一個形式,所以我們需要定義一些額外的 String
static final String STATE_SCORE = "playerScore"; static final String STATE_LEVEL = "playerLevel"; // ... @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putInt(STATE_SCORE, mCurrentScore); savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel); // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); }
儲存完狀態之後,為了能在系統重新例項化這個 Activity 的時候恢復先前被系統殺死前的狀態,我們在 onCreate
方法裡把原來儲存的值重新取出來:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Always call the superclass first // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state mCurrentScore = savedInstanceState.getInt(STATE_SCORE); mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); } else { // Probably initialize members with default values for a new instance } // ... }
當然,恢復這個操作也可以在 onRestoreInstanceState
這個方法實現:
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
解放你的雙手
上面的方案當然是正確的。但是並不優雅,為了保持變數的值,引入了兩個方法 ( onSaveInstanceState
和 onRestoreInstanceState
) 和兩個常量 ( 為了儲存兩個變數而定義的兩個常量,僅僅為了放到 Bundle
裡面)。
為了更好地解決這個問題,我寫了 SaveState 這個外掛:
在使用了 SaveState 這個外掛以後,保持 Activity 的狀態的寫法如下:
public class MyActivity extends Activity {
@AutoRestore
int myInt;
@AutoRestore
IBinder myRpcCall;
@AutoRestore
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Your code here
}
}
沒錯,你只需要在需要保持的變數上標記 @AutoRestore
註解即可,無需去管那幾個煩人的 Activity 回撥,也不需要定義多餘的 String
型別 key 常量。
那麼,除了 Activity 以外,Fragment 能自動保持狀態嗎?答案是: Yes!
public class MyFragment extends Fragment {
@AutoRestore
User currentLoginUser;
@AutoRestore
List<Map<String, Object>> networkResponse;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// Your code here
}
}
使用方法和 Activity 一模一樣!不止如此,使用場景還可以推廣到 View
, 從此,你的自定義 View,也可以把狀態保持這個任務交給 SaveState :
public class MyView extends View {
@AutoRestore
String someText;
@AutoRestore
Size size;
@AutoRestore
float[] myFloatArray;
public MainView(Context context) {
super(context);
}
public MainView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MainView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
現在就使用 SaveState
首先,在專案根目錄的 build.gradle
檔案中增加以下內容:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
// your other dependencies
// dependency for save-state
classpath "io.github.prototypez:save-state:${latest_version}"
}
}
然後,在 application 和 library 模組的 build.gradle
檔案中應用外掛:
apply plugin: 'com.android.application'
// apply plugin: 'com.android.library'
apply plugin: 'save.state'
萬事具備!再也不需要寫煩人的回撥,因為你的時間非常值錢!做了一點微小的工作,如果我幫你節省下來了喝一杯咖啡的時間,希望你可以幫我點一個 Star,謝謝 :)