简体   繁体   English

在Android中动态引用Strings.xml中的字符串

[英]Dynamically referencing a String in Strings.xml in Android

Say I have the following my strings.xml file: 说我有以下我的strings.xml文件:

<string name="string0">Lorem</string>
<string name="string1">ipsum</string>
<string name="string2">dolor</string>

In my activity an ID is set based on the clicking of a button. 在我的活动中,基于单击按钮来设置ID。 If the top button is clicked the id is 0, middle is 1 and bottom button is 2. 如果单击顶部按钮,则ID为0,中间为1,底部按钮为2。

What would the syntax look like for referencing one of the three strings? 引用三个字符串之一的语法是什么样的?

I know R.string.string0 works but I want to do something equivalent to: 我知道R.string.string0可以工作,但是我想做一些等效的事情:

R.string["string"+currentID]

where I derive the string to use based on the ID. 我根据ID派生要使用的字符串。

Just not sure what the syntax would look like in Java/Android. 只是不确定语法在Java / Android中是什么样。

Thanks in advance, Tony 预先感谢,托尼

您不仅可以在资源中使用字符串数组,还可以使用单独的字符串条目吗?

That's a bad approach. 那是一个不好的方法。 It's slow. 太慢了 It'd be better to have an internal integer array with all the R.string IDs. 最好有一个带有所有R.string ID的内部整数数组。

If you really insist on using a string-based approach, use Resources.getIdentifier() . 如果您真的坚持使用基于字符串的方法,请使用Resources.getIdentifier()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM