Categories
android dynamic option-type parameters string

Are parameters in strings.xml possible? [duplicate]

327

In my Android app I’am going to implement my strings with internationalization. I have a problem with the grammar and the way sentences build in different languages.

For example:

“5 minutes ago” – English

“vor 5 Minuten” – German

Can I do something like the following in strings.xml?

<string name="timeFormat">{0} minutes ago</string>

And then some magic like

getString(R.id.timeFormat, dynamicTimeValue)

This behaviour would solve the other problem with different word orders as well.

0

    401

    Yes, just format your strings in the standard String.format() way.

    See the method Context.getString(int, Object...) and the Android or Java Formatter documentation.

    In your case, the string definition would be:

    <string name="timeFormat">%1$d minutes ago</string>
    

    0

      359

      If you need two variables in the XML, you can use:

      %1$d text... %2$d or %1$s text... %2$s for string variables.

      Example :

      strings.xml

      <string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>
      

      activity.java

      String site = "site.tld";
      String days = "11";
      
      //Toast example
      String notyet = getString(R.string.notyet, site, days);
      Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();
      

      2

      • 8

        The order is not as important as you say. The numbers in the string is actually the order of the parameter. Depending on language you could have the numbers in different order.

        – Flaxie

        Jan 16, 2015 at 8:10

      • Important to note that you need to change the xml first, or else the .java code getString will not compile, because getString needs to know in advance how many parameters it needs.

        Jan 27, 2021 at 18:28

      40

      If you need to format your strings using String.format(String, Object…), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

      <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
      

      In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

      Resources res = getResources();
      String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
      

      If you wish more look at: http://developer.android.com/intl/pt-br/guide/topics/resources/string-resource.html#FormattingAndStyling