简体   繁体   中英

how to use Java/Android string formatting on <string-array>

How can is use string formatting on the
<string-array><item> - resource in Android?

Should i do it like in the following example(and how should i do it if yes)...

<string-array name="notification-msgs">
   <item>%s sent you a message.</item>
   <item>%s answered to your Story</item>
</string-array>

or what kind of technique is common to use in this case? I only know how to Format string resources.(with getString(R.id.mystring,replacevalue) ) Thanks for any help!
EDIT:

  • I tried to use getStringArray(), but this method does not accept more then one argument, which just is an Array-Ressource.

Unfortunately there is no direct way provided by Android to achieve this. Best you can do is:

String.format(getResources().getStringArray(R.array.notification-msgs)[0], "Someone")

Android supports formatting with getString(String str,Object... args) . Link here
Or you can wrap formatting with a method.

public static String formatString(String pure,Object... args){
     return String.format(pure,args);
}
//Or 
public static String formatString(int id,Context context,Object... args){
     String pure = context.getString(id);
     return String.format(pure,args);
}

I personally prefer second approach, it is easy to mutable in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM