使用 Kotlin 的 Android SharedPreferences

在本教程中,我们将学习如何使用Kotlin在Android应用程序中实现SharedPreferences。

什么是Android SharedPreferences?

SharedPreferences是Android API的一部分,自API级别1起。它是一个 接口 ,允许我们在本地存储/修改/删除数据。通常,它用于缓存用户本地数据,如登录表单。数据以键值对的形式存储。您可以创建多个文件来保存[SharedPreferences](/community/tutorials/android-shared-preferences-example-tutorial)数据。

SharedPreferences方法

让我们来看看SharedPreferences的一些重要方法。

  • getSharedPreferences(String,int)方法用于检索SharedPferences的实例。其中String是SharedPreferences文件的名称,int是传递的上下文。
  • SharedPferences.Editor()用于编辑SharedPferences中的值。
  • 我们可以调用Commit()Apply()来保存SharedPreferences文件中的值。Commit()立即保存值,而Apply()异步保存值。

使用Kotline设置/检索值的共享首选项

我们可以通过以下方式使用Kotlin在SharedPreference实例上设置值。

1val sharedPreference =  getSharedPreferences("PREFERENCE_NAME",Context.MODE_PRIVATE)
2var editor = sharedPreference.edit()
3editor.putString("username","Anupam")
4editor.putLong("l",100L)
5editor.commit()

用于检索值:

1sharedPreference.getString("username","defaultName")
2sharedPreference.getLong("l",1L)

共享首选项实例上允许的类型为:Android共享首选项types

清除和删除SharedPreferences记录的Kotlin代码

我们也可以通过调用clear()Remove(字符串键)方法来清除所有值或移除特定的值。

1editor.clear()
2editor.remove("username")

注意:不考虑在提交或应用之后对编辑器所做的更改。上面从SharedPference保存和检索值的方法与我们在Java中所做的几乎相同。那么Kotlin的魔力在哪里? 这就是我们接下来将通过一个示例Android应用程序看到的。

Android共享首选Kotlin项目结构

Android共享首选项kotlin project在这个应用程序中,我们将有一个登录屏幕,允许我们保存/清除表单数据。

1.布局代码

active_main.xml布局文件的代码如下所示。

 1<?xml version="1.0" encoding="utf-8"?>
 2<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3    android:layout_width="match_parent"
 4    android:layout_height="match_parent"
 5    android:orientation="vertical">
 6
 7    <EditText
 8        android:id="@+id/inUserId"
 9        android:layout_width="match_parent"
10        android:layout_height="wrap_content"
11        android:layout_alignParentTop="true"
12        android:hint="User ID"
13        android:inputType="number" />
14
15    <EditText
16        android:id="@+id/inPassword"
17        android:layout_width="match_parent"
18        android:layout_height="wrap_content"
19        android:layout_below="@+id/inUserId"
20        android:hint="Password"
21        android:inputType="textPassword" />
22
23    <Button
24        android:id="@+id/btnSave"
25        android:layout_width="wrap_content"
26        android:layout_height="wrap_content"
27        android:layout_below="@+id/inPassword"
28        android:text="SAVE USER DATA" />
29
30    <Button
31        android:id="@+id/btnClear"
32        android:layout_width="wrap_content"
33        android:layout_height="wrap_content"
34        android:layout_alignParentLeft="true"
35        android:layout_alignParentStart="true"
36        android:layout_below="@+id/btnSave"
37        android:text="CLEAR USER DATA" />
38
39    <Button
40        android:id="@+id/btnShow"
41        android:layout_width="wrap_content"
42        android:layout_height="wrap_content"
43        android:layout_alignParentRight="true"
44        android:layout_below="@+id/inPassword"
45        android:text="SHOW" />
46
47    <Button
48        android:id="@+id/btnShowDefault"
49        android:layout_width="wrap_content"
50        android:layout_height="wrap_content"
51        android:layout_alignParentEnd="true"
52        android:layout_alignParentRight="true"
53        android:layout_below="@+id/btnSave"
54        android:text="Show Default" />
55
56</RelativeLayout>

2.MainActivity Kotlin代码

MainActivity.ktKotlin类的代码如下所示。

 1package com.journaldev.androidlysharedpreferences
 2
 3import android.content.Context
 4import android.content.SharedPreferences
 5import android.support.v7.app.AppCompatActivity
 6import android.os.Bundle
 7import android.preference.PreferenceManager
 8import android.view.View
 9import com.journaldev.androidlysharedpreferences.PreferenceHelper.defaultPreference
10import com.journaldev.androidlysharedpreferences.PreferenceHelper.password
11import com.journaldev.androidlysharedpreferences.PreferenceHelper.userId
12import com.journaldev.androidlysharedpreferences.PreferenceHelper.clearValues
13import com.journaldev.androidlysharedpreferences.PreferenceHelper.customPreference
14
15import kotlinx.android.synthetic.main.activity_main.*
16
17class MainActivity : AppCompatActivity(), View.OnClickListener {
18
19    val CUSTOM_PREF_NAME = "User_data"
20
21    override fun onCreate(savedInstanceState: Bundle?) {
22        super.onCreate(savedInstanceState)
23        setContentView(R.layout.activity_main)
24
25        btnSave.setOnClickListener(this)
26        btnClear.setOnClickListener(this)
27        btnShow.setOnClickListener(this)
28        btnShowDefault.setOnClickListener(this)
29
30    }
31
32    override fun onClick(v: View?) {
33        val prefs = customPreference(this, CUSTOM_PREF_NAME)
34        when (v?.id) {
35            R.id.btnSave -> {
36                prefs.password = inPassword.text.toString()
37                prefs.userId = inUserId.text.toString().toInt()
38            }
39            R.id.btnClear -> {
40                prefs.clearValues
41
42            }
43            R.id.btnShow -> {
44                inUserId.setText(prefs.userId.toString())
45                inPassword.setText(prefs.password)
46            }
47            R.id.btnShowDefault -> {
48
49                val defaultPrefs = defaultPreference(this)
50                inUserId.setText(defaultPrefs.userId.toString())
51                inPassword.setText(defaultPrefs.password)
52            }
53        }
54    }
55
56}
57
58object PreferenceHelper {
59
60    val USER_ID = "USER_ID"
61    val USER_PASSWORD = "PASSWORD"
62
63    fun defaultPreference(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
64
65    fun customPreference(context: Context, name: String): SharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE)
66
67    inline fun SharedPreferences.editMe(operation: (SharedPreferences.Editor) -> Unit) {
68        val editMe = edit()
69        operation(editMe)
70        editMe.apply()
71    }
72
73    var SharedPreferences.userId
74        get() = getInt(USER_ID, 0)
75        set(value) {
76            editMe {
77                it.putInt(USER_ID, value)
78            }
79        }
80
81    var SharedPreferences.password
82        get() = getString(USER_PASSWORD, "")
83        set(value) {
84            editMe {
85                it.putString(USER_PASSWORD, value)
86            }
87        }
88
89    var SharedPreferences.clearValues
90        get() = { }
91        set(value) {
92            editMe {
93                it.clear()
94            }
95        }
96}

多亏了Kotlin Android扩展,我们不必为每个XML视图使用findViewByID。在上面的代码中,我们使用关键字`class](/community/tutorials/kotlin-singleton-companion-object)创建了一个[Singleton对象。我们声明了一个名为Editme()的内联高阶函数,该函数保存编辑操作的逻辑。我们为每个值创建了单独的属性。我们使用Get和Set Kotlin属性来检索和设置共享首选项中的数据。Kotlin减少了代码的冗长,看起来干净多了。此外,我们可以通过使用下面所示的另一个Kotlin高阶函数来使其更简洁。

 1fun SharedPreferences.Editor.put(pair: Pair<String, Any>) {
 2    val key = pair.first
 3    val value = pair.second
 4    when(value) {
 5        is String -> putString(key, value)
 6        is Int -> putInt(key, value)
 7        is Boolean -> putBoolean(key, value)
 8        is Long -> putLong(key, value)
 9        is Float -> putFloat(key, value)
10        else -> error("Only primitive types can be stored in SharedPreferences")
11    }

在设置值时,我们执行以下操作:

1var SharedPreferences.password
2        get() = getString(USER_PASSWORD, "")
3        set(value) {
4            editMe {
5                it.put(USER_PASSWORD to value)
6            }
7        }

这是科特林能让你接触到的最接近的英语语言。运行中的上述应用程序的输出如下所示。安卓共享首选项Kotlin应用程序output

您可以从以下链接下载源代码:AndroidlySharedPreferences

Published At
Categories with 技术
Tagged with
comments powered by Disqus