How to easily iterate over all strings within the “strings.xml” resource file?

眉间皱痕 提交于 2019-12-14 02:18:17

问题


I created an application that uses the TTS engine to send feedback to the user. With the aim to improve the performance, I used the synthesizeToFile and addSpeech methods, but strings of text to be synthesized are inside the strings.xml file, so I have to invoke these methods for each string that is spoken by the TTS engine.

Since the TTS engine uses only strings whose name begins with tts_, is it possible to easily iterate over all strings that begin with tts_ within the strings.xml file?


回答1:


You can give them all (while defining) the resource name as "prefix"+(1..n). And in the code use,

int resid=<constant>;
for(i=1;resid!=0;i++){
        resid = this.getResources().getIdentifier("prefix"+i, "strings", this.getPackageName());
}



回答2:


You can get all the strings in strings.xml via reflection, and filter out only the ones you need, like so:

for (Field field : R.string.class.getDeclaredFields())
{
  if (Modifier.isStatic(field.getModifiers()) && !Modifier.isPrivate(field.getModifiers()) && field.getType().equals(int.class))
  {
    try
    {
      if (field.getName().startsWith("tts_"))
      {
        int id = field.getInt(null);
        // do something here...
      }
    } catch (IllegalArgumentException e)
    {
      // ignore
    } catch (IllegalAccessException e)
    {
      // ignore
    }
  }
}



回答3:


You could put these TTS strings into a TypedArray.




回答4:


In all my projects, i just observed that the value of strings in R.java starts with 0x7f050000 and it counts upwards, like 0x7f050001, 0x7f050002, 0x7f050003,....

You could just ++ them :D

Hope it helps :)



来源:https://stackoverflow.com/questions/10633456/how-to-easily-iterate-over-all-strings-within-the-strings-xml-resource-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!