下面列出了怎么用android.support.v4.content.SharedPreferencesCompat的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 保存数据
* @param context
* @param key
* @param value
*/
public static void put(Context context, String key, Object value) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else {
editor.putString(key, value.toString());
}
SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
}
/**
* 移除数据
* @param context
* @param key
*/
public static void remove(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
}
/**
* 清空保存数据
* @param context
*/
public static void clear(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
}
@Override
public void onSkinChange(int mode, Activity activity) {
SharedPreferences preferences = activity.getSharedPreferences("NightOwlDemo",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("mode", mode);
SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
}
public void putInt(final String key, final int value) {
mEditor.putInt(key, value);
SharedPreferencesCompat.EditorCompat.getInstance().apply(mEditor);
}
public void putLong(final String key, final long value) {
mEditor.putLong(key, value);
SharedPreferencesCompat.EditorCompat.getInstance().apply(mEditor);
}
public void putString(final String key, final String value) {
mEditor.putString(key, value);
SharedPreferencesCompat.EditorCompat.getInstance().apply(mEditor);
}
public void putFloat(final String key, final float value) {
mEditor.putFloat(key, value);
SharedPreferencesCompat.EditorCompat.getInstance().apply(mEditor);
}
public void putBoolean(final String key, final boolean value) {
mEditor.putBoolean(key, value);
SharedPreferencesCompat.EditorCompat.getInstance().apply(mEditor);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void putStringSet(final String key, final Set<String> values) {
mEditor.putStringSet(key, values);
SharedPreferencesCompat.EditorCompat.getInstance().apply(mEditor);
}