xml:
<?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"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请填入姓名"
android:textColor="@color/black"
/>
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请填入姓名"></EditText>
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="存储到SharedPreferences"></Button>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="读取SharedPreferences"></Button>
</LinearLayout>
MainAcyivity:
package com.example.sharedpreferencesdemo;
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.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn1,btn2;
EditText et;
// 定义全局变量
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(this);
btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(this);
et = findViewById(R.id.et);
// 获取对象
sp = getSharedPreferences("config",MODE_PRIVATE);
}
@Override
public void onClick(View view) {
switch (view.getId()){
// 存储:
case R.id.btn1:
String etString = et.getText().toString();
saveData(etString);
break;
// 读取:
case R.id.btn2:
String content = sp.getString("content","");
Toast.makeText(this,"欢迎光临"+content,Toast.LENGTH_SHORT).show();
break;
}
}
public void saveData(String string){
// 获取编辑器
SharedPreferences.Editor editor = sp.edit();
// 写入数据
editor.putString("content",string);
// 提交
editor.commit();
}
}