访问 Android 首选项键的最佳方式

发布于 2024-12-16 01:44:35 字数 255 浏览 2 评论 0原文

访问和存储 Android 首选项键的最佳方式是什么?

我不想总是手动输入它们,因为那样我就无法快速更改它们。

目前我只看到两种可能性:

  1. final static key_xxx
    但它们不能在preference.xml中引用

  2. 将键放在strings.xml中
    但随后它们可能会被翻译,这也不是我想要的。

是否还有更多存储首选项键的可能性?

what is the best way to access and store android preference keys?

I don't want to always enter them manually beacuse then I can't change them quickly.

At the moment I only see two possibilities:

  1. final static key_xxx
    but they can't be referred in the preference.xml

  2. put the keys in the strings.xml
    but then they may be translatet, and that too is not what I want.

Are there any more possibilities of storing preference keys?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不再让梦枯萎 2024-12-23 01:44:35

第一个解决方案是最常见的。是的,它们不能在首选项文件中自动引用,但至少键在整个代码中是一致的。如果您需要在某个时候更改密钥,那么是的,您将必须考虑到这一点,并在需要时从旧密钥复制值。但是,您很少会更改密钥(如果有的话)。

根据我的经验,您想要更改密钥的唯一时间是其行为发生变化(例如,它可能具有的值)。当我想忽略其中设置的任何值并从头开始时,我通常会更改键的名称。因此,您可以看到这样一个事实:首选项文件不会将对键名称的引用存储为功能,而不是错误:)。

The first solution is the most common one. Yes, they can't be automatically referred to in the preferences file, but at least the keys will be consistent throughout your code. If you need to change a key at some point then yes, you will have to account for that and copy the value from the old key if needed. However, you will rarely change keys (if at all).

From my experience, the only time you want to change a key is if its behavior changes (e.g. the possible values it can have). I usually change the key's name when I want to ignore whatever value was set in there and start from scratch. So you can look at the fact that the preference file doesn't store the reference to the key name as a feature, not a bug :).

牛↙奶布丁 2024-12-23 01:44:35

更多可能性:

  1. 将其放在资产中的首选项文件中。
  2. 将其放入首选项数据库表中。
  3. 不要打扰,只需对密钥进行硬编码即可。

但说真的,最好的办法是将键放在 strings.xml 中。别担心,除非您手动为每个语言环境指定键值,否则键不会被翻译;即便如此,这也不是问题,因为您的代码和 xml 都会引用相同的本地化首选项键值。

More possibilities:

  1. put it in preferences file in assets.
  2. put it in preferences database table.
  3. don't bother and just hardcode the keys.

Seriously though, you best bet is to put the keys in strings.xml. Don't worry, the keys won't be translated unless you manually specify key value for each locale; and even then it's not a problem cause both your code and your xml will reference the same localized preference key value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文