使用示例

  • 保存一个基本数据获取获取单个基本数据

    1. sp().putString("key","hhhhh")
  • 保存多个基本数据

    1. sp().edit {
    2. putInt(SpKey.TEST,2)
    3. putString(SpKey.HELLO,"hello")
    4. }
  • 保存对象和获取对象

    1. sp().putAny(SpKey.TEST,TestBean(true,"alice"))
    2. //获取保存对象
    3. val test = sp().getAny<TestBean>(SpKey.TEST)
  • 保存集合和获取集合

    1. val list = listOf(TestBean(true,"alice"),TestBean(true,"bob"))
    2. sp().putAny(SpKey.TEST,list)*/
    3. //获取保存的list
    4. /* val testList = sp().getList<TestBean>(SpKey.TEST)
    5. Log.e("MMM", "testSp: $testList" )*
  • 删除数据

    1. //清除某个数据
    2. sp().clear(SpKey.HELLO)
    3. //清除当前name下的所有数据
    4. sp().clear()

    封装类

    ```kotlin fun Any.sp(name: String = LUtilsConfig.SP_DEFAULT_NAME) = LUtilsConfig.getContext().getSharedPreferences(name, Context.MODE_PRIVATE)

/**

批处理 */ fun SharedPreferences.edit(action: SharedPreferences.Editor.() -> Unit) { edit().apply { action() }.apply() }

/**

对象操作 */ fun SharedPreferences.putAny(key: String, obj: Any?) { putString(key, obj?.toJson() ?: “”) }

/* 获取任意对象 */ fun SharedPreferences.getAny(key: String, clazz: Class): T? { val string = getString(key, null) if (string.isNullOrEmpty()) return null return string.toAny(clazz) }

inline fun SharedPreferences.getAny(key: String): T? { val string = getString(key, null) if (string.isNullOrEmpty()) return null return string.toAny() }

/* 获取list */ fun SharedPreferences.getList(key: String, clazz: Class): List? { val string = getString(key, null) if (string.isNullOrEmpty()) return null return string.toList2(clazz) }

inline fun SharedPreferences.getList(key: String): List? { val string = getString(key, null) if (string.isNullOrEmpty()) return null return string.toList2() }

/**

put系列 */ fun SharedPreferences.putString(key: String, value: String?) { edit { putString(key, value ?: “”) } }

fun SharedPreferences.putInt(key: String, value: Int) { edit { putInt(key, value) } }

fun SharedPreferences.putBoolean(key: String, value: Boolean) { edit { putBoolean(key, value) } }

fun SharedPreferences.putFloat(key: String, value: Float) { edit { putFloat(key, value) } }

fun SharedPreferences.putLong(key: String, value: Long) { edit { putLong(key, value) } }

fun SharedPreferences.putStringSet(key: String, value: Set) { edit { putStringSet(key, value) } }

fun SharedPreferences.clear(key: String) { edit { remove(key) } }

fun SharedPreferences.clear() { edit { clear() } } ```