Dav*_* R. 28 android preferences classcastexception
我有一个preferences.xml,如下所示:
<?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>
Run Code Online (Sandbox Code Playgroud)
当我执行sp.getString("sample","3.0")时,它工作正常并返回一个字符串,但它不应该是一个字符串,它应该是一个浮点数.运行sp.getFloat("sample",3.0f)会抛出ClassCastException,因为它是一个字符串.
我应该在XML中放置什么以便将首选项存储为浮点数?
MrS*_*ake 44
在您的首选项xml中,您可以添加android:numeric带有值的选项"integer".这样,用户应该只能输入有效的整数值.
加载设置时,您应该尝试自己将其解析为数字(因为所有值都存储为字符串(@下面的@mba)):
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14217 次 |
| 最近记录: |