【问题标题】:Android Studio: SharedPreferencesAndroid Studio:共享首选项
【发布时间】:2026-02-09 14:30:02
【问题描述】:

我在主要活动中有一个文本框,在创建活动中有一个编辑文本框。我使用创建活动将我的文本生成到主要活动中的文本框。这部分有效。

但是,当我切换回创建活动时,主活动中 texbox 中的文本消失了。

即使在切换活动后,我也想将文本保存在文本框中

【问题讨论】:

标签: android sharedpreferences


【解决方案1】:

查看SharedPreferences 以在活动中保存String 的值。

  • 在 MainActivity 中,读取 SharedPreferencesGet the String value 来自SharedPreferences(默认值设置为String“默认值”)并将该值设置为TextView

    SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE);
    // read from SharedPreferences
    // get the string value using the key "string" set when writing to the shared preferences
    // return string default otherwise
    String string = sharedPreferences.getString("string", "Default Value");
    
    // get the TextView
    TextView textView = (TextView) findViewById(R.id.textView);
    // setText on TextView
    textView.setText(string);
    
  • 在 CreateActivity 中,写入SharedPreferences。在活动的生命周期方法onPause() 中,通过使用getText() 方法从EditText 获取值来写入SharedPreferences

    @Override
    protected void onPause() {
        super.onPause();
        // write to SharedPreferences with edit
        getSharedPreferences("sharedPrefs", MODE_PRIVATE).edit()
                .putString("string", editText.getText().toString())
                .apply();
    }
    

快速说明:当使用getSharedPreferences() 获取SharedPreferences 时,请务必使用相同的名称——在我们的例子中为"sharedPrefs"

刚刚经过试验和测试 - 欢迎随时提问!

【讨论】:

    【解决方案2】:

    有一些项目适合您: 1.将文本设为缓存,切换到主Activity时,从缓存中取出文本并设置文本到文本框,可以使用SharePrefrence或DiskCache来保存缓存 2.将主Activity设为Single,比如在AndroidManifest.xml中设置launchMode="singleTask",应该让主Activity在切换到创建Activity时不会结束 有我的想法,你可以试试,祝你好运!

    【讨论】: