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

后端 未结 4 1522
刺人心
刺人心 2021-01-22 08:36

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 addSp

相关标签:
4条回答
  • 2021-01-22 08:39

    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());
    }
    
    0 讨论(0)
  • 2021-01-22 08:48

    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
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-22 08:59

    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 :)

    0 讨论(0)
  • 2021-01-22 09:03

    You could put these TTS strings into a TypedArray.

    0 讨论(0)
提交回复
热议问题