个性化阅读
专注于IT技术分析

Kotlin android sharedpreferences用法

Android共享首选项允许活动或应用程序以键和值的形式存储和检索数据。即使关闭应用程序, 存储在应用程序中的数据仍会保留, 直到删除或清除为止。

Android设置文件使用“共享首选项”将应用程序设置数据以XML文件的形式存储在data / data / {application package} / share_prefs目录下。

要在我们的应用程序中访问“共享首选项”, 我们需要使用以下任何一种方法来获取它的实例。

  • getPreferences()
  • getSharedPreferences()
  • getDefaultSharedPreferences()
val sharedPreferences: SharedPreferences = this.getSharedPreferences(String preferences_fileName, int mode)

这里preferences_fileName是共享首选项文件名, mode是文件的操作模式。

对首选项数据的修改是通过SharedPreferences.Editor对象执行的。

val editor:SharedPreferences.Editor =  sharedPreferences.edit()

要删除应用程序的首选项数据, 我们调用方法:

  • editor.remove(“ key”):删除指定键的值
  • editor.clear():删除所有首选项数据

当我们执行以下任何操作时, 共享首选项中存储的数据将丢失:

  • 卸载应用程序。
  • 通过设置清除应用程序数据。

Kotlin Android SharedPreferences示例

在此示例中, 我们将从EditText获取输入数据(ID和名称)并将其存储在首选项文件中。通过在Button上执行单击操作, 可以检索并在TextView中显示此首选项数据, 并清除(删除)该首选项数据。

activity_main.xml

在activity_main.xml布局文件中添加以下代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.srcmini02.com.kotlinsharedpreference.MainActivity">

    <TableLayout
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="0"
                android:layout_marginLeft="10sp"
                android:layout_marginStart="10sp"
                android:text="Enter Id"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

            <EditText
                android:id="@+id/editId"
                android:layout_width="201dp"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:layout_marginLeft="50sp"
                android:layout_marginStart="50sp"
                android:hint="id"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
        </TableRow>


        <TableRow>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="0"
                android:layout_marginLeft="10sp"
                android:layout_marginStart="10sp"
                android:text="Enter Name"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

            <EditText
                android:id="@+id/editName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:layout_marginLeft="50sp"
                android:layout_marginStart="50sp"
                android:hint="name"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
        </TableRow>

        <TableRow android:layout_marginTop="60dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="0"
                android:layout_marginLeft="10sp"
                android:layout_marginStart="10sp"
                android:text="Your Id"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

            <TextView
                android:id="@+id/textViewShowId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:layout_marginLeft="50sp"
                android:layout_marginStart="50sp"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
        </TableRow>

        <TableRow android:layout_marginTop="20dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="0"
                android:layout_marginLeft="10sp"
                android:layout_marginStart="10sp"
                android:text="Your Name"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

            <TextView
                android:id="@+id/textViewShowName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:layout_marginLeft="50sp"
                android:layout_marginStart="50sp"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:orientation="horizontal"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent">

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save" />

        <Button
            android:id="@+id/view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="View" />

        <Button
            android:id="@+id/clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Clear" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

MainActivity.kt

在MainActivty.kt类文件中添加以下代码。在此类中, 我们将共享首选项数据以键值形式存储在kotlinsharedpreference中。

package example.srcmini02.com.kotlinsharedpreference

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView



class MainActivity : AppCompatActivity() {

    private val sharedPrefFile = "kotlinsharedpreference"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val inputId = findViewById<EditText>(R.id.editId)
        val inputName = findViewById<EditText>(R.id.editName)
        val outputId = findViewById<TextView>(R.id.textViewShowId)
        val outputName = findViewById<TextView>(R.id.textViewShowName)

        val btnSave = findViewById<Button>(R.id.save)
        val btnView = findViewById<Button>(R.id.view)
        val btnClear = findViewById<Button>(R.id.clear)
        val sharedPreferences: SharedPreferences = this.getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE)
        btnSave.setOnClickListener(View.OnClickListener {
            val id:Int = Integer.parseInt(inputId.text.toString())
            val name:String = inputName.text.toString()
            val editor:SharedPreferences.Editor =  sharedPreferences.edit()
            editor.putInt("id_key", id)
            editor.putString("name_key", name)
            editor.apply()
            editor.commit()
        })
        btnView.setOnClickListener {
            val sharedIdValue = sharedPreferences.getInt("id_key", 0)
            val sharedNameValue = sharedPreferences.getString("name_key", "defaultname")
            if(sharedIdValue.equals(0) && sharedNameValue.equals("defaultname")){
                outputName.setText("default name: ${sharedNameValue}").toString()
                outputId.setText("default id: ${sharedIdValue.toString()}")
            }else{
                outputName.setText(sharedNameValue).toString()
                outputId.setText(sharedIdValue.toString())
            }

        }
        btnClear.setOnClickListener(View.OnClickListener {
            val editor = sharedPreferences.edit()
            editor.clear()
            editor.apply()
            outputName.setText("").toString()
            outputId.setText("".toString())
        })
    }
}

输出:

Kotlin android sharedpreferences
Kotlin android sharedpreferences
Kotlin android sharedpreferences

使用SharedPreferences, 我们可以通过将用户的状态(数据)存储在首选项文件中来在应用程序中创建登录和注销功能。

赞(0)
未经允许不得转载:srcmini » Kotlin android sharedpreferences用法

评论 抢沙发

评论前必须登录!