访问 Android 首选项键的最佳方式
访问和存储 Android 首选项键的最佳方式是什么?
我不想总是手动输入它们,因为那样我就无法快速更改它们。
目前我只看到两种可能性:
final static key_xxx
但它们不能在preference.xml中引用将键放在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:
final static key_xxx
but they can't be referred in the preference.xmlput 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个解决方案是最常见的。是的,它们不能在首选项文件中自动引用,但至少键在整个代码中是一致的。如果您需要在某个时候更改密钥,那么是的,您将必须考虑到这一点,并在需要时从旧密钥复制值。但是,您很少会更改密钥(如果有的话)。
根据我的经验,您想要更改密钥的唯一时间是其行为发生变化(例如,它可能具有的值)。当我想忽略其中设置的任何值并从头开始时,我通常会更改键的名称。因此,您可以看到这样一个事实:首选项文件不会将对键名称的引用存储为功能,而不是错误:)。
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 :).
更多可能性:
但说真的,最好的办法是将键放在 strings.xml 中。别担心,除非您手动为每个语言环境指定键值,否则键不会被翻译;即便如此,这也不是问题,因为您的代码和 xml 都会引用相同的本地化首选项键值。
More possibilities:
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.