如何声明 Android 首选项的类型?
我有一个如下所示的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>
当我执行 sp.getString("sample", "3.0") 时,它工作正常并返回一个字符串,但它不应该是一个字符串,它应该是一个浮点数。运行 sp.getFloat("sample", 3.0f) 会引发 ClassCastException,因为它是字符串。
我应该在 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>
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.
What should I put in the XML so that the preference is stored as a float?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的首选项 xml 中,您可以添加一个值为
“integer”
的选项android:numeric
。这样用户应该只能输入有效的整数值。加载设置时,您应该尝试自己将其解析为数字(因为所有值都存储为 字符串(下面的@mbaird)):
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.When loading the setting you should try to parse it to a number yourself (as all values are stored as Strings (@mbaird below)):
如果您使用内置的首选项屏幕 API,而不是编写自己的首选项对话框或活动,那么您在某些方面将会受到一些限制。例如,EditTextPreference 始终将值存储为字符串。
来自API 文档:
我注意到,您似乎没有任何方法可以限制用户仅在文本字段中输入有效的浮点数。如果他们输入“abc”你会怎么做?
If you are using the built in preferences screen API instead of writing your own preferences Dialogs or Activities, then you are going to be a bit limited in some respects. For example EditTextPreference will always store the value as a String.
From the API Doc:
I note that there doesn't appear to be any way for you to restrict the user to just typing in a valid floating point number in your text field. What would you do if they typed in "abc"?
正如姆贝尔德指出的那样,你不能强制存储为浮点数。
但是您可以将
EditTextPreference
更改为普通的Preference
视图,并为其实现click
事件。这样,您将能够创建并显示自己的对话框,用于编辑值,因此您可以限制格式并将其另存为 Float 到首选项文件中。As mbaird pointed out you can't force to store as Float.
But you can change the
EditTextPreference
to a plainPreference
view, and implement theclick
event for it. This way you will be able to create and show your own Dialog, for edit the value, and thus you can restrict the format and save as Float to the preference file.