我希望我的应用程序将 textView2 保存在共享首选项中。这是我当前的共享首选项代码,用于保存复选框的状态(选中/未选中)。
private boolean getFromSP(String key){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
return bifrostPrefs.getBoolean(key, false);
}
private void saveInSp(String key,boolean value){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = bifrostPrefs.edit();
editor.putBoolean(key, value);
editor.commit();
}
我以前从未真正使用过共享首选项,所以我真的不知道如何创建一个新的共享首选项来保存我的 textview2。
最佳答案
你不能。
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.
Al-thought你可以存储TextView的值
//To get stored value
private String getString(String key){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
return bifrostPrefs.getString(key, "");
}
..
//To Save value
private void saveString(String key, String value){
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = bifrostPrefs.edit();
editor.putString(key, value);
editor.commit();
}
<小时/>
如何使用这些方法
将此代码放在要保存 TextVIew 值的位置
//To save value of TextView
if (!TextUtils.isEmpty(aTextView.getText())) {
saveString("aTextView", aTextView.getText().toString());
}
//To Read and show into TextVIew
aTextView.setText(getString("aTextView"));
关于java - 如何在共享首选项中保存 TextView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17086234/