12.27

 package com.example.myapp;

 

import android.content.SharedPreferences;

import android.os.Bundle;

import android.preference.PreferenceManager;

import android.widget.EditText;

 

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    private EditText editText;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        editText = findViewById(R.id.editText);

 

        // 从默认的 Shared Preferences 中读取数据

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

        String savedText = preferences.getString("saved_text", "");

        editText.setText(savedText);

    }

 

    @Override

    protected void onPause() {

        super.onPause();

 

        // 将用户输入的文本保存到 Shared Preferences 中

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

        SharedPreferences.Editor editor = preferences.edit();

        editor.putString("saved_text", editText.getText().toString());

        editor.apply();

    }

}

<?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="16dp">

 

    <EditText

        android:id="@+id/editText"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Enter text"

        android:textSize="18sp" />

 

</LinearLayout>

posted @ 2024-12-27 20:15  赵千万  阅读(1)  评论(0编辑  收藏  举报