我有一个preferences.xml看起来是这样的:
I have a preferences.xml that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:name="Sample"
android:enabled="true"
android:persistent="true"
android:summary="Sample"
android:defaultValue="3.0"
android:title="Sample"
android:key="sample" />
</PreferenceScreen>
当我这样做sp.getString(样品,3.0),它工作正常,并返回一个字符串,但它不应该是一个字符串,它应该是一个浮动。运行sp.getFloat(样品,3.0F)抛出一个ClassCastException,因为它是一个字符串。
When I do sp.getString("sample", "3.0"), it works fine and returns a string, but it shouldn't be a string, it should be a float. Running sp.getFloat("sample", 3.0f) throws a ClassCastException because it is a string.
我应该把在XML使得preference存储为浮?
What should I put in the XML so that the preference is stored as a float?
在你的preferences XML中可以添加的选项 Android版本:数字
的值整数
。这样,用户只能够进入一个有效的整数值。
In your preferences xml you can add an option android:numeric
with the value "integer"
. This way the user should only be able to enter a valid integer value.
加载当设置,你应该尝试将它解析为数字自己(因为所有的值都为的字符串(@mbaird下)):
When loading the setting you should try to parse it to a number yourself (as all values are stored as Strings (@mbaird below)):
try {
float val = Float.parseFloat(sp.getString("sample", "3.0f"));
} catch (NumberFormatException e) {
// "sample" was not an integer value
// You should probably start settings again
}
上一篇:android-开放的画廊,并选择图像和视频画廊、图像、视频、android
下一篇:在布局设置文字颜色在TextView中/ main.xml中主要布局文件中没有引用colors.xml文件。 (就是了#RRGGBB代替@色/ text_color)布局、文件、颜色、文字