3.29

所花时间(包括上课):1.5

打码量(行):220

博客量(篇):1

了解到知识点:学习SharedPreferences

 

 import android.content.Context;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    private static final String SHARED_PREF_NAME = "my_shared_pref";

    private static final String KEY_USERNAME = "username";

 

    private EditText editTextUsername;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        editTextUsername = findViewById(R.id.edit_text_username);

 

        // 加载保存的数据

        loadUsername();

 

        // 保存数据到 SharedPreferences

        saveUsername();

    }

 

    private void saveUsername() {

        String username = editTextUsername.getText().toString().trim();

 

        // 获取 SharedPreferences 实例

        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

 

        // 获取 SharedPreferences.Editor 对象

        SharedPreferences.Editor editor = sharedPreferences.edit();

 

        // 存储数据

        editor.putString(KEY_USERNAME, username);

 

        // 提交数据

        editor.apply();

    }

 

    private void loadUsername() {

        // 获取 SharedPreferences 实例

        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

 

        // 读取数据

        String username = sharedPreferences.getString(KEY_USERNAME, "");

 

        // 在 EditText 中显示数据

        editTextUsername.setText(username);

    }

}

posted @ 2024-03-29 21:30  赵千万  阅读(7)  评论(0编辑  收藏  举报