一个人如何申报一个Android preference的类型?类型、个人、Android、preference

2023-09-05 10:01:14 作者:回不去的曾经℡

我有一个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
}