<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入数据"
android:textSize="25sp"
android:layout_margin="20dp"/>
<Button
android:id="@+id/put"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="存"
android:onClick="save"
android:textSize="25sp" />
<Button
android:id="@+id/get"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="取"
android:textSize="25sp"
android:onClick="get"/>
</LinearLayout>
package com.example.sharedpreferences;
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.text);
}
public void save(View view) {
String content = editText.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences("spRecord", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("content", content);
editor.commit();
Toast.makeText(MainActivity.this, "清空内容", Toast.LENGTH_SHORT);
editText.setText("");
}
public void get(View view) {
SharedPreferences sharedPreferences = getSharedPreferences("spRecord", MODE_PRIVATE);
String content = sharedPreferences.getString("content", "");
editText.setText(content);
}
}