【起航計劃 008】2015 起航計劃 Android APIDemo的魔鬼步伐 07 App->Activity->Persistent State 儲存狀態 SharedPreferences onPause onResume

來源:互聯網
上載者:User

標籤:

Android 提供了多種儲存資料的方法,其中最簡單的是使用Shared Preferences. Shared Preferences 可以儲存 Key/value 對,Shared Preferences 支援存取 boolean, float ,long ,integer, string ,最常用的使用Shared Preferences是用來儲存一些應用偏好。此外的一個方法是使用onSaveInstanceState(),這是特別用來儲存UI 狀態的。

此外的一個方法是使用onSaveInstanceState(),這是特別用來儲存UI 狀態的。

App->Activity->Persistent State 使用了Shared Preferences來保持部分UI狀態(TextView的值)。

建立或是修改Shared Preferences,使用getSharedPreferences(String name, int mode)方法。Shared Preferences 用於單個Application不同Activity之間共用一些資料,但不能用於不同Application之間共用資料。

SharedPreferences.Editor 用來給Shared Preferences添加資料: editor.putXXX(key,value):

    /**     * Any time we are paused we need to save away the current state, so it     * will be restored correctly when we are resumed.     */    @Override    protected void onPause() {        super.onPause();        SharedPreferences.Editor editor = getPreferences(0).edit();        editor.putString("text", mSaved.getText().toString());        editor.putInt("selection-start", mSaved.getSelectionStart());        editor.putInt("selection-end", mSaved.getSelectionEnd());        editor.commit();    }

讀取Shared Preference: pref.getXXX(key)

    /**     * Upon being resumed we can retrieve the current state.  This allows us     * to update the state if it was changed at any time while paused.     */    @Override    protected void onResume() {        super.onResume();        SharedPreferences prefs = getPreferences(0);         String restoredText = prefs.getString("text", null);        if (restoredText != null) {            mSaved.setText(restoredText, TextView.BufferType.EDITABLE);            int selectionStart = prefs.getInt("selection-start", -1);            int selectionEnd = prefs.getInt("selection-end", -1);            if (selectionStart != -1 && selectionEnd != -1) {                mSaved.setSelection(selectionStart, selectionEnd);            }        }    }

 

Persistent State 示範了如何使用Shared Preferences在Activity 恢複時保持EditText的內容。 單是更一般的方法是使用onSaveInstanceState.

 

【起航計劃 008】2015 起航計劃 Android APIDemo的魔鬼步伐 07 App->Activity->Persistent State 儲存狀態 SharedPreferences onPause onResume

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.