【发布时间】:2015-04-29 04:51:09
【问题描述】:
我制作了一个食物计算器,它计算卡路里(来自食物类型)和重量(基于使用 EditText 的用户输入)并在 TextView 中显示这些。然后我将如何获取 textView 中显示的值并将其保存到 SharedPreference 中?
【问题讨论】:
标签: java android android-studio sharedpreferences
我制作了一个食物计算器,它计算卡路里(来自食物类型)和重量(基于使用 EditText 的用户输入)并在 TextView 中显示这些。然后我将如何获取 textView 中显示的值并将其保存到 SharedPreference 中?
【问题讨论】:
标签: java android android-studio sharedpreferences
要保存该值,请将其写入 SharedPreferences。
private static final String VALUE_TAG = "myTag";
Context c = this; //this for Activity. For Fragment use getActivity();
你总是给一个键赋值,我称之为“myKey”
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(VALUE_TAG, 5);
editor.apply();
然后检索它:
int defaultValue = 42;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
int retrievedValue = sp.getInt(VALUE_TAG , defaultValue);
其中42是键“myKey”没有值时返回的值;
【讨论】:
PreferenceManager.getDefaultSharedPreferences() 方法中的 this 参数是应用程序的上下文。此外,用于保存/获取首选项的字符串应该是类内的public static final String 字段(以避免拼写错误)