SharedPreferences
SharedPreferences,是一种轻量级的数据存储方式,采用Key/value的方式
进行映射,Sp通常用于记录一些参数配置、行为标记等!
1、获得mSharedPreferences的实例
mSharedPreferences = getSharedPreferences("data",MODE_PRIVATE);
2、通过Eidt更新数据,获取一个Edit对象,所有对数据的操作都需要经过Edit
mEditor = mSharedPreferences.edit();
layout:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="15dp"> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入内容"/> <Button android:id="@+id/btn_save" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="保存" android:textSize="20sp"/> <Button android:id="@+id/btn_show" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="显示" android:textSize="20sp"/> <TextView android:id="@+id/tv_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"/> </LinearLayout>
Activity:

package com.example.helloworld.datastorage; import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.helloworld.R; public class SharedPreferencesActivity extends AppCompatActivity { private EditText mEtName; private Button mBtnSave,mBtnShow; private TextView mTvContent; private SharedPreferences mSharedPreferences; private SharedPreferences.Editor mEditor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shared_preferences2); mEtName = findViewById(R.id.et_name); mBtnSave = findViewById(R.id.btn_save); mBtnShow = findViewById(R.id.btn_show); mTvContent = findViewById(R.id.tv_content); //获得mSharedPreferences的实例 mSharedPreferences = getSharedPreferences("data",MODE_PRIVATE); //获取一个Edit对象,所有对数据的操作都需要经过Edit mEditor = mSharedPreferences.edit(); mBtnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //把EditText里的文本通过SharedPreferences保存起来 mEditor.putString("name",mEtName.getText().toString());//获取EditText里的文本内容 mEditor.commit();//提交,commmit才回生效 } }); mBtnShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取文件中的值 mTvContent.setText(mSharedPreferences.getString("name","")); } }); } }
把EditText里的文本通过SharedPreferences保存起来,获取之后在EditText中显示