Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 989
enzom83 Avatar asked May 17 '12 09:05

enzom83


People also ask

What is the use of clean strings XML file?

Clean strings.xml file helps to easily maintain and translate strings to different languages — screen after screen. If you want you can create strings.xml file per screen — settings-strings.xml, profile-strings.xml.

What is the role of string in XML?

Here we explained the basics of String and their role in XML which is quite beneficial in hierarchical data structures also done with real-time examples of how the strings are extracted from the schema file. They provide an ability to describe element type with a string like a string to be started from upper case / lower case or any other ranges.

How to initialize string in XML?

How to Initialize String in XML? A string is initialized in the Element name with the type ‘string’. For example: It returns the string in the element name, if it is an integer then it returns a value. If the type doesn’t have any content then it could be declared as a string, not as any data types.

Is it possible to iterate over each character in a string?

A thing as simple as iterating over each character in a string is one of them. Let’s explore some methods and discuss their upsides and downsides. Before we start, we need to come back to a much more basic question. Nowadays with ECMAScript 2015 (ES6), there are two ways of accessing a single character:


1 Answers

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
    }
  }
}
like image 71
Logan Pickup Avatar answered Sep 28 '22 05:09

Logan Pickup