編輯:關於 Android 程式設計
SharedPreferences 是 Android 中常用的輕量級資料儲存方式,適合保存設定、標記等簡單的鍵值資料。以下將其常見操作封裝成一個工具類,方便在專案各處統一呼叫。
/**
* 偏好參數存儲工具類
*/
public class SharedPrefsUtil {
/** 數據存儲的 XML 名稱 **/
public final static String NAME = "QY";
/** 存儲數據(Long) */
public static void putLongValue(Context context, String key, long value) {
context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.edit().putLong(key, value).commit();
}
/** 存儲數據(Int) */
public static void putIntValue(Context context, String key, int value) {
context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.edit().putInt(key, value).commit();
}
/** 存儲數據(String) */
public static void putStringValue(Context context, String key, String value) {
context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.edit().putString(key, value).commit();
}
/** 存儲數據(boolean) */
public static void putBooleanValue(Context context, String key, boolean value) {
context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.edit().putBoolean(key, value).commit();
}
/** 取出數據(Long) */
public static long getLongValue(Context context, String key, long defValue) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.getLong(key, defValue);
}
/** 取出數據(int) */
public static int getIntValue(Context context, String key, int defValue) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.getInt(key, defValue);
}
/** 取出數據(boolean) */
public static boolean getBooleanValue(Context context, String key, boolean defValue) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.getBoolean(key, defValue);
}
/** 取出數據(String) */
public static String getStringValue(Context context, String key, String defValue) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.getString(key, defValue);
}
/** 清空所有數據 */
public static void clear(Context context) {
context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.edit().clear().commit();
}
/** 移除指定數據 */
public static void remove(Context context, String key) {
context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
.edit().remove(key).commit();
}
}
NAME 管理同一組偏好設定,讓讀寫操作集中管理。defValue 預設值參數,當 key 不存在時可回傳合理的預設值。clear() 與 remove(),分別用於清空全部資料與移除單一鍵值。小提醒:此處使用 commit() 為同步寫入,會阻塞主執行緒;若在意效能,可改用非同步的 apply() 方法。此外,SharedPreferences 不適合儲存大量資料或敏感個資,這類情境建議改用資料庫或加密儲存方案。
Unity 滑頁嵌套實作:解決 ScrollRect 橫向與縱向捲動衝突
簡介 在 Unity 的 UGUI 系統中,ScrollRect 是製作捲動列表與滑頁界面的常用元件。不過,當橫向滑頁裡又需要嵌入縱向滑頁時,兩層 ScrollRect
Android 熱補丁動態修復框架小結
一、概述 GitHub 上已有許多熱修復動態修復框架,例如 Tinker、HotFix、Nuwa 等。它們的核心思路相近,主要圍繞 Android 的 ClassLoad
圖案解鎖實作分享:整合開源的 android-lockpattern 庫
基於技術分享、學習互助的精神,這篇記錄一款開源的 Android 圖案解鎖(九宮格解鎖)實作的整合方式。它也是參考 Android 系統自帶的圖案鎖源碼改造而來,可以直接
Android 螢幕適配方案:用百分比取代無限堆疊的 dimens
為什麼網頁從不抱怨適配 做 Android 開發的人,大概都對螢幕適配有過一段痛苦回憶。各種尺寸組合起來,簡直無解。 但換個角度想:電腦螢幕的解析度加上手機解析度,種類遠