Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 輕量數據持久化:SharedPreferences 實戰(以飛行模式開關為例)

編輯:關於 Android 程式設計

需求很常見:模擬系統設置中的「飛行模式」開關,切換狀態後重啟應用仍能記住上次的選擇。這正是 SharedPreferences 的適用場景——以鍵值對形式保存少量簡單數據。

一、布局文件 fragment_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="70dip"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/airplane" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title"
        android:text="@string/content" />

    <CheckBox
        android:id="@+id/cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:focusable="false"
        android:clickable="false" />

</RelativeLayout>

二、字符串資源 strings.xml

<resources>
    <string name="app_name">layout</string>
    <string name="action_settings">Settings</string>
    <string name="airplane">飛行模式</string>
    <string name="content">關閉網絡連接</string>
    <string name="ari_open">飛行模式已開啟</string>
    <string name="ari_close">飛行模式已關閉</string>
</resources>

三、MainActivity 代碼

public class MainActivity extends Activity {

    private TextView tv_content;
    private CheckBox cb;
    private RelativeLayout rl;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

        // 將需要記錄的數據保存在 config.xml 文件中
        sp = getSharedPreferences("config", MODE_PRIVATE);
        // 也可以使用 getPreferences(MODE_PRIVATE),此時會以當前 Activity 類名作為文件名

        boolean flymode = sp.getBoolean("flymode", false);

        tv_content = (TextView) findViewById(R.id.tv_content);
        cb = (CheckBox) findViewById(R.id.cb);
        rl = (RelativeLayout) findViewById(R.id.rl);

        if (flymode) {
            tv_content.setText(R.string.ari_open);
            cb.setChecked(true);
        } else {
            tv_content.setText(R.string.ari_close);
            cb.setChecked(false);
        }

        rl.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (cb.isChecked()) {
                    cb.setChecked(false);
                    tv_content.setText(R.string.ari_close);
                    Editor editor = sp.edit();
                    editor.putBoolean("flymode", false);
                    editor.commit();
                } else {
                    cb.setChecked(true);
                    tv_content.setText(R.string.ari_open);
                    Editor editor = sp.edit();
                    editor.putBoolean("flymode", true);
                    editor.commit();
                }
            }
        });
    }
}

四、要點說明

  • 獲取實例:getSharedPreferences("config", MODE_PRIVATE) 會生成一個名為 config.xml 的配置文件,存放於應用的私有目錄下。
  • 讀取數據:sp.getBoolean("flymode", false),第二個參數是默認值,當鍵不存在時返回。
  • 寫入數據:先 sp.edit() 取得 Editor,再 putBoolean / putString 等,最後必須調用 commit()(或 apply())提交,否則不會持久化。
  • 適用場景:SharedPreferences 適合保存配置項、開關狀態、用戶偏好等小型數據,不適合存放大量數據或結構化數據。

至此,一個具備狀態記憶能力的開關就完成了。重啟應用後,界面會自動還原上次的選擇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved