kotlin写安卓的sharepreference存储功能

安卓项目里面,基本会使用的功能shareperference 的存储功能,用来储存一些状态或者字符串等等,kotlin 在这方面提供了很好的实现:
见代码如下:
功能:今天就来实现以下,界面A 跳转到界面B ,在A里面设置一个值,在B里面取值显示:
先来看下工具类的代码:

/**
 * Created by ${李伟} on 2017/8/29 0029.
 */
class Preference(val context: Context, val string:String, val default : T) : ReadWriteProperty {

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return findPreference(string, default)
    }

    val prefs by lazy{context.getSharedPreferences("Realnen",Context.MODE_PRIVATE)}

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(string, value)
    }

    private fun putPreference(name:String,value:A)= with(prefs.edit()){
        when(value){//if语句 现在在kotlin中是表达式
            is Long -> putLong(name,value)
            is String -> putString(name,value)
            is Int -> putInt(name,value)
            is Boolean -> putBoolean(name,value)
            is Float -> putFloat(name,value)
            else ->   putString(name,serialize(value))
        }.apply()
    }
    private fun  findPreference(name: String, default: U): U = with(prefs) {
        val res: Any = when (default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("This type can not be saved")
        }
        res as U
    }

    /**
     * 序列化对象

     * @param person
     * *
     * @return
     * *
     * @throws IOException
     */
    @Throws(IOException::class)
    private fun serialize(obj: A): String {
        val byteArrayOutputStream = ByteArrayOutputStream()
        val objectOutputStream = ObjectOutputStream(
                byteArrayOutputStream)
        objectOutputStream.writeObject(obj)
          var serStr = byteArrayOutputStream.toString("ISO-8859-1")
        serStr = java.net.URLEncoder.encode(serStr, "UTF-8")
        objectOutputStream.close()
        byteArrayOutputStream.close():

       return serStr    }

}

是不是被震撼到了,哈哈,真心好
界面A代码:

class MainActivity : AppCompatActivity(){

    private var first: String by Preference(this, "first", "")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        main_text.text="你好,Kotlin"
        main_text.setTextColor(R.color.colorPrimaryDark)
    }

    /**
     * kotlin的界面相互的之间的跳转
     */
    fun intent(view: View){
        //获取intent对象
        val inetnt = Intent()
        intent.setClass(this,KotlinActivity::class.java)
        startActivity(intent)
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onResume() {
        super.onResume()
    }

    fun btn_setname(view:View){
        first = "李伟"
    }



}

调用只需要一行,修改也是,是不是很省事
界面B:

class KotlinActivity : AppCompatActivity() {

    private var first: String by Preference(this, "first", "")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin)
        main_text.setText(first)
    }

就是简单取值显示:
今天就到这里吧,有不懂的同学可以留言。

你可能感兴趣的:(安卓开发,Kotlin)