0

I have some localized string formats with format arguments in different orders. For example I have the phrase synced 12 files on 6/29/2018 which is to be displayed to the user. Where the 12 and the 6/29/2018 are just placeholders. So the string in my resources looks like

 <string name="n_synced_on_date" formatted="false">"%d files synced on %s"</string>

The trouble is some of the translators would like to write it

 <string name="n_synced_on_date" formatted="false">"bla %s bla bla bla %d bla"</string>

So when I run my code

 text = String.format(getString(R.string.n_synced_on_date), numberOfFiles, dateString)

It will crash for any language that reverses the format arguments.

I was hoping that I could use Kotlin string templates so my resources could be defined as

<string name="n_synced_on_date" formatted="false">"$NUMBER files synced on $DATESTRING"</string>

this would allow translators to put the words in any order but according to this link How to apply template to a string returned from a function this is not possible.

My current lousy approach is to catch the number format exception and try the string format with the arguments reversed. I was hoping to find a nice clean solution.

Marc
  • 1,159
  • 17
  • 31

1 Answers1

2

As this answer explain, you can proceed like this giving an index to the arguments:

<string name="n_synced_on_date" formatted="false">"%1$d files synced on %2$s"</string>
<string name="n_synced_on_date" formatted="false">"bla %2$s bla bla bla %1$d bla"</string>

and then you can run the code like you're already doing :

String.format(getString(R.string.n_synced_on_date), numberOfFiles, dateString)
ollaw
  • 2,086
  • 1
  • 20
  • 33