preferenceActivity:保存的值作为整数 [英] PreferenceActivity: save value as integer
问题描述
使用我的preferences活动一个简单的的EditText preference
:
Using a simple EditTextPreference
in my preferences activity:
<EditTextPreference
android:key="SomeKey"
android:title="@string/some_title"
android:summary="..."
android:numeric="integer"
android:maxLength="2"
/>
有没有一种方法,此配置价值将被保存为整数?现在看来,它只是允许输入数字,但该值仍然保存为字符串:
Is there a way that this configuration value would be saved as integer? Seems now it just allows to enter numbers, but the value is still saved as string:
电话:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int value = preferences.getInt("SomeKey", -1);
抛出我 java.lang.ClassCastException:java.lang.String中
和
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String value = preferences.getString("SomeKey", "-1");
检索值成功。
retrieves the value successfully.
如何让 preferenceActivity
默认保存的值作为整数?
How to make PreferenceActivity
to save value as integer by default?
推荐答案
您可以扩展的EditText preference:
You could extend EditTextPreference:
public class IntEditTextPreference extends EditTextPreference {
public IntEditTextPreference(Context context) {
super(context);
}
public IntEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IntEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected String getPersistedString(String defaultReturnValue) {
return String.valueOf(getPersistedInt(-1));
}
@Override
protected boolean persistString(String value) {
return persistInt(Integer.valueOf(value));
}
}
这将是更好地覆盖onSetInitialValue()和的setText()方法,但你会复制一些code从基类。上述方案是simplier,但它是相当棘手 - 弦的方法做一些与整数。尽量不要扩展此类进一步的; - )
It would be better to overwrite onSetInitialValue() and setText() methods, but then you would have to copy some code from a base class. Above solution is simplier, but it's quite tricky - "string" methods do something with ints. Try to not extend this class further ;-)
您可以通过使用它从XML
You could use it from XML by:
<package.name.IntEditTextPreference
android:key="SomeKey"
android:title="@string/some_title"
android:summary="..."
android:numeric="integer"
android:maxLength="2"
/>
这篇关于preferenceActivity:保存的值作为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!