不需要再手寫 onSaveInstanceState 了,因?yàn)槟愕臅r(shí)間非常值錢

如果你是一個(gè)有經(jīng)驗(yàn)的 Android 程序員,那么你肯定手寫過許多 onSaveInstanceState 以及 onRestoreInstanceState 方法用來保持 Activity 的狀態(tài),因?yàn)?Activity 在變?yōu)椴豢梢娨院?,系統(tǒng)隨時(shí)可能把它回收用來釋放內(nèi)存。重寫 Activity 中的 onSaveInstanceState 方法 是 Google 推薦的用來保持 Activity 狀態(tài)的做法。

Google 推薦的最佳實(shí)踐

onSaveInstanceState 方法會(huì)提供給我們一個(gè) Bundle 對(duì)象用來保存我們想保存的值,但是 Bundle 存儲(chǔ)是基于 key - value 這樣一個(gè)形式,所以我們需要定義一些額外的 String 類型的 key 常量,最后我們的項(xiàng)目中會(huì)充斥著這樣代碼:

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

保存完?duì)顟B(tài)之后,為了能在系統(tǒng)重新實(shí)例化這個(gè) Activity 的時(shí)候恢復(fù)先前被系統(tǒng)殺死前的狀態(tài),我們?cè)?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
    }
    // ...
}

當(dāng)然,恢復(fù)這個(gè)操作也可以在 onRestoreInstanceState 這個(gè)方法實(shí)現(xiàn):

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

解放你的雙手

上面的方案當(dāng)然是正確的。但是并不優(yōu)雅,為了保持變量的值,引入了兩個(gè)方法 ( onSaveInstanceStateonRestoreInstanceState ) 和兩個(gè)常量 ( 為了存儲(chǔ)兩個(gè)變量而定義的兩個(gè)常量,僅僅為了放到 Bundle 里面)。

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

save-state-logo

在使用了 SaveState 這個(gè)插件以后,保持 Activity 的狀態(tài)的寫法如下:

public class MyActivity extends Activity {

    @AutoRestore
    int myInt;

    @AutoRestore
    IBinder myRpcCall;

    @AutoRestore
    String result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Your code here
    }
}

沒錯(cuò),你只需要在需要保持的變量上標(biāo)記 @AutoRestore 注解即可,無需去管那幾個(gè)煩人的 Activity 回調(diào),也不需要定義多余的 String 類型 key 常量。

那么,除了 Activity 以外,F(xiàn)ragment 能自動(dòng)保持狀態(tài)嗎?答案是: 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 一模一樣!不止如此,使用場(chǎng)景還可以推廣到 View, 從此,你的自定義 View,也可以把狀態(tài)保持這個(gè)任務(wù)交給 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);
    }

}

現(xiàn)在就使用 SaveState

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

首先,在項(xiàng)目根目錄的 build.gradle 文件中增加以下內(nèi)容:

buildscript {

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

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

然后,在 applicationlibrary 模塊的 build.gradle 文件中應(yīng)用插件:

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

萬事具備!再也不需要寫煩人的回調(diào),因?yàn)槟愕臅r(shí)間非常值錢!做了一點(diǎn)微小的工作,如果我?guī)湍愎?jié)省下來了喝一杯咖啡的時(shí)間,希望你可以幫我點(diǎn)一個(gè) Star,謝謝 :)

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容