MMKV 本地存储
先引入库:
implementation 'com.tencent:mmkv-static:1.2.10'
这封装一个类
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.Nullable
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.activity_login_by_password.*
import java.lang.Exception
/**
* 保存本地数据KEY
*/
object Save {
/**
* 常用保存
*/
fun set(key: String, @Nullable value: Any) {
when (value) {
is String -> MMKV.defaultMMKV().encode(key, value)
is Boolean -> MMKV.defaultMMKV().encode(key, value)
is Long -> MMKV.defaultMMKV().encode(key, value)
is Int -> MMKV.defaultMMKV().encode(key, value)
is Double -> MMKV.defaultMMKV().encode(key, value)
is Float -> MMKV.defaultMMKV().encode(key, value)
else -> throw Exception("暂时不支持这类型");
}
}
/**
* 读取
*/
fun get(key: String): String? {
return MMKV.defaultMMKV().decodeString(key)
}
fun getLong(key: String): Long {
return MMKV.defaultMMKV().decodeLong(key)
}
fun getInt(key: String): Int {
return MMKV.defaultMMKV().decodeInt(key)
}
fun getBool(key: String): Boolean {
return MMKV.defaultMMKV().decodeBool(key)
}
fun getDouble(key: String): Double {
return MMKV.defaultMMKV().decodeDouble(key)
}
fun getFloat(key: String): Float {
return MMKV.defaultMMKV().decodeFloat(key)
}
/**
* 直接将值保存到EditText
*/
fun setEditText(key: String, edit: EditText) {
var value = MMKV.defaultMMKV().decodeString(key)
value.let {
edit.setText(it)
}
}
/**
* 直接将值保存到TextView
*/
fun setTextView(key: String, edit: TextView) {
var value = MMKV.defaultMMKV().decodeString(key)
value.let {
edit.text = it
}
}
}