【发布时间】:2016-06-25 21:41:44
【问题描述】:
在下面的SSCCE中,思路是主activity中有一个按钮,当用户点击时,(调用showCheckBoxPreferencesValue()方法)preferences.xml中定义的唯一preference的默认值(使用android:default_value) 应显示在此按钮下方的文本框中。
为了让这个默认值显示在文本框中,我使用sharedPreferences.getString() 方法并将Preference does not exist 作为第二个参数传递,这意味着如果首选项(key 作为第一个参数传递)确实似乎不存在,然后将字符串Preference does not exist 设置为文本框。 (Source)
这正在发生吗?我做错了什么?见最后截图。
res/xml/preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<EditTextPreference android:key="@string/preferences_editTextPreference_key"
android:title="@+id/preferences_editTextPreference_title"
android:defaultValue="@string/preferences_editTextPreference_defaultValue" />
</PreferenceScreen>
MainActivity.java:
public class MainActivity extends Activity {
private String EDIT_TEXT_PREFERENCE_KEY;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.mainActivity_textView);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
public void showCheckBoxPreferencesValue(View view) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
EDIT_TEXT_PREFERENCE_KEY = getResources().getString(R.string.preferences_editTextPreference_key);
String editTextPreferenceValue = sharedPreferences.getString(EDIT_TEXT_PREFERENCE_KEY,
"Preference does not exist");
textView.setText("Checkbox Preference Value: " + editTextPreferenceValue);
}
}
res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Preferences Practice</string>
<string name="mainActivity_button">Show EditText Preference\'s Value</string>
<string name="preferences_editTextPreference_key">EditTextPreferenceKey</string>
<string name="preferences_editTextPreference_title">EditTextPreference Title</string>
<string name="preferences_editTextPreference_defaultValue">EditTextPreference Default Value String</string>
</resources>
【问题讨论】:
-
您的代码似乎没问题。但是我不确定使用对字符串(在资源文件中)的引用来命名 KEY 是一个好的解决方案。例如,考虑您有多个语言资源文件的情况:键名将更改并破坏您的系统。也许您可以解决卸载和重新安装应用程序的问题,因为文档说“只有在过去从未调用过此方法时,此方法才会设置默认值”
标签: android sharedpreferences android-preferences android-sharedpreferences