我发现的大多数示例都显示了在xml中设置默认值的方法。 我需要在代码隐藏中设置默认值。
注意:
的值Environment.getExternalStorageDirectory().getPath() + "/BasicCommunicationWithAndroid.log"
是/storage/sdcard0/BasicCommunicationWithAndroid.log 所以它不是空的也不是空字符串
public class SettingsFragment extends PreferenceFragment
{
private Preference _pref_log_logFilenameOnSDCard;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
loadPreferences();
}
private void loadPreferences()
{
_pref_log_logFilenameOnSDCard = (Preference) findPreference("pref_log_logFilenameOnSDCard");
_pref_log_logFilenameOnSDCard.setDefaultValue(Environment.getExternalStorageDirectory().getPath() + "/BasicCommunicationWithAndroid.log");
}
}
在onCreate(..)的MainActivity中 我有:
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
答案 0 :(得分:7)
我遇到了同样的问题并解决了这个问题:
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.layout.settings_fragment);
ListPreference listPreference = (ListPreference) findPreference("user");
if(listPreference.getValue()==null) {
// to ensure we don't get a null value
// set first value by default
String defaultValue = "Smith";
PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("user", defaultValue);
listPreference.setValue(defaultValue);
}
// this part just shows how I set a summary field on the element onChange and initially
listPreference.setSummary(listPreference.getValue().toString());
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
}
}
所以只需使用这部分:
PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("user", defaultValue);