不需要再手寫 onSaveInstanceState 了,因為你的時間非常值錢


如果你是一個有經驗的 Android 程序員,那么你肯定手寫過許多 onSaveInstanceState 以及 onRestoreInstanceState 方法用來保持 Activity 的狀態,因為 Activity 在變為不可見以后,系統隨時可能把它回收用來釋放內存。重寫 Activity 中的 onSaveInstanceState 方法 是 Google 推薦的用來保持 Activity 狀態的做法。

Google 推薦的最佳實踐

onSaveInstanceState 方法會提供給我們一個 Bundle 對象用來保存我們想保存的值,但是 Bundle 存儲是基於 key - value 這樣一個形式,所以我們需要定義一些額外的 String 類型的 key 常量,最后我們的項目中會充斥着這樣代碼:

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

解放你的雙手

上面的方案當然是正確的。但是並不優雅,為了保持變量的值,引入了兩個方法 ( onSaveInstanceStateonRestoreInstanceState ) 和兩個常量 ( 為了存儲兩個變量而定義的兩個常量,僅僅為了放到 Bundle 里面)。

為了更好地解決這個問題,我寫了 SaveState 這個插件:

save-state-logo

在使用了 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

引入 SaveState 的方法也十分簡單:

首先,在項目根目錄的 build.gradle 文件中增加以下內容:

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        // your other dependencies

        // dependency for save-state
        classpath "io.github.prototypez:save-state:${latest_version}"
    }
}

然后,在 applicationlibrary 模塊的 build.gradle 文件中應用插件:

apply plugin: 'com.android.application'
// apply plugin: 'com.android.library'
apply plugin: 'save.state'

萬事具備!再也不需要寫煩人的回調,因為你的時間非常值錢!做了一點微小的工作,如果我幫你節省下來了喝一杯咖啡的時間,希望你可以幫我點一個 Star,謝謝 😃

SaveState Github 地址:https://github.com/PrototypeZ/SaveState


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM