設定ファイルを扱う [設定]
SharedPreferencesを使うと、キーと値のセットになったxmlを作成してくれる。設定情報などを扱うのに便利。
以下のgetStringの例だが、getIntなど色々ある。
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
SharedPreferences mSharedpreferences =
getSharedPreferences(PREFERRENCES_FILE_NAME, MODE_PRIVATE); SharedPreferences.Editor editor =mSharedpreferences.edit(); //保存
editor = mSharedpreferences.edit();
editor.putString(KEY, value);
editor.commit();
//データの取得
String value = mSharedpreferences.getString(KEY, "");
//データの削除
editor.remove(KEY); editor.commit();
//クリア
editor.clear(); editor.commit();
設定画面 [設定]
設定画面はPreferenceActivityを使うと楽。
まずresのlayout内に設定画面用のレイアウトを作成する。
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="@string/setting_title"> <EditTextPreference android:key="setting_web" android:title="@string/setting_web" android:summary="@string/setting_web_summary" android:dialogTitle="@string/setting_web_dialogtitle" /> <EditTextPreference android:key="setting_blog" android:title="@string/setting_blog" android:summary="@string/setting_blog_summary" android:dialogTitle="@string/setting_blog_dialogtitle" /> </PreferenceCategory> </PreferenceScreen>
EditTextPreferenceしか載せてないが、他にもある。
http://developer.android.com/reference/android/preference/PreferenceActivity.html
次にActivityの作成
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.preference); }
設定画面で編集すると、SharedPreferencesに自動的に保存される。これは便利。
PreferenceManager.getDefaultSharedPreferences(context);