【问题标题】:Android integer within listpreferencelistpreference中的Android整数
【发布时间】:2015-08-25 15:22:09
【问题描述】:

我有一个偏好 xml 文件和一个列表偏好。

listpreference entryValues 和 entries 在 array.xml 文件中。

这是问题所在,条目/条目值包含“10 mb/s”,我想从该条目/选择的任何内容中获取 int 值。

这给了我一个错误但是,这里是代码:

    TextView t = (TextView)findViewById(R.id.textView1);

    String result = sp.getString("BITRATE", "8");

    int i = Integer.parseInt(result.substring(result.lastIndexOf(" mb/s")));

    t.setText("Int value: " + i);

正如我所说,这给了我一个错误,我找不到问题。

感谢您的帮助!

最终固定代码

    TextView t = (TextView)findViewById(R.id.textView1);

    String result = sp.getString("BITRATE", "3");

    int intRes = Integer.parseInt(result);

    t.setText("Int value: " + intRes);

我还将偏好 entryValues 项更改为仅整数而不是前 10mb/s 到仅 10。

【问题讨论】:

    标签: android xml parsing


    【解决方案1】:

    使您的entryValues 数组仅包含整数。 entries 在向用户显示时使用,entryValues 是存储在您的首选项中的内容(并且不显示)。两个数组不必具有相同的内容,但它们应该具有相同的项数。

    <string-array name="bitrate_entries">
        <item>10 mb/s</item>
        <item>25 mb/s</item>
        <item>50 mb/s</item>
    </string-array>
    
    <string-array name="bitrate_entry_values">
        <item>10</item>
        <item>25</item>
        <item>50</item>
    </string-array>
    

    现在你只需要使用Integer.parseInt()

    【讨论】:

    • 嗯,没有错误,虽然它没有返回我的首选项 listpreference 值,但它在我调用 sp.getInt 时返回默认值,它是 3,但在我的 ListPReference 默认值中它是 8。跨度>
    • @YOYOYO 确保您使用的是正确的共享首选项密钥。您还可以在首选项 xml 中指定 android:defaultValue
    • 没关系,修好了!谢谢一堆真的帮了我:)
    • @YOYOYO 你应该问一个新问题。目前尚不清楚您要做什么。
    猜你喜欢
    • 1970-01-01
    • 2011-09-02
    • 2011-04-05
    • 2012-06-02
    • 1970-01-01
    • 2015-05-02
    • 2015-02-01
    • 2011-04-24
    • 2012-08-04
    相关资源
    最近更新 更多