【问题标题】:How does one declare the type of an Android preference?如何声明 Android 偏好的类型?
【发布时间】:2011-01-28 06:30:04
【问题描述】:

我有一个看起来像这样的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 中添加什么以便将首选项存储为浮点数?

【问题讨论】:

    标签: android preferences classcastexception


    【解决方案1】:

    如果您使用内置的首选项屏幕 API 而不是编写自己的首选项对话框或活动,那么您将在某些方面受到限制。例如,EditTextPreference 将始终将值存储为字符串。

    来自the API Doc

    此首选项将存储一个字符串 进入 SharedPreferences。

    我注意到,您似乎没有任何方法可以限制用户只在文本字段中输入有效的浮点数。如果他们输入“abc”,你会怎么做?

    【讨论】:

    • “您似乎没有任何方法可以限制用户只在您的文本字段中输入有效的浮点数” 实际上至少在今天是有的。 android:numeric="decimal" 是更好的方法,但还有其他方法。
    【解决方案2】:

    在您的首选项 xml 中,您可以添加一个带有值 "integer" 的选项 android:numeric。这样用户应该只能输入一个有效的整数值。

    加载设置时,您应该尝试自己将其解析为一个数字(因为所有值都存储为Strings(以下@mbaird)):

    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
    }
    

    【讨论】:

    • 似乎可以工作,即使 Eclipse 没有为“android:numeric”部分提供 Intellisense ......因此我从来没有想过,谢谢!
    • 这很好用。我不依赖于用户输入,而是一个引用字符串浮点数的列表。非常容易做和容易处理。
    【解决方案3】:

    正如 mbaird 指出的那样,您不能强制存储为 Float。

    但是您可以将EditTextPreference 更改为普通的Preference 视图,并为其实现click 事件。这样您就可以创建和显示您自己的 Dialog,用于编辑值,因此您可以限制格式并将作为 Float 保存到首选项文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多