【情况一】含有变量的语句未实现单复数功能,直接加载字串
步骤一:将常规字串加载方式改用getQuantityString()方法加载字串,修改点为修改调用的方法名和复制增加一个数字参数这两点即可,举例如下:
修改前:
mString = res.getString(R.string. numberOfSongsAvailable, count); |
修改后(其中第一count是用于选取字串,第二个count用于替换%d变量,修改时复制一次即可):
mString = res. getQuantityString(R.plurals. numberOfSongsAvailable, count, count); |
步骤二:在XML资源文件中,将英文原字串由string修改为plurals方式,包含”one” 、”zero”、”two”、”few”、”many”、”other”六种quality,其中”one”对应英文单数形式,”other”、”zero”、”two”、 ”few”、 ”many”全部对应英文复数形式
修改前:
<string name="numberOfSongsAvailable">%d songs found.</ string > |
修改后:
<plurals name="numberOfSongsAvailable"> <item quantity="one">%d song found.</item> <item quantity="zero">%d songs found.</item> <item quantity="two">%d songs found.</item> <item quantity="few">%d songs found.</item> <item quantity="many">%d songs found.</item> <item quantity="other">%d songs found.</item> </plurals> |
步骤三:给六种quality加上注释,标注其代表数字样例,其中”zero”样例为0,”one”样例为1,”two”样例为2,”few”样例为3,”many”样例为11,”other”样例为2.07,示例如下:
<plurals name="numberOfSongsAvailable"> <!-- 此处添加该条字串场景描述 --> <item quantity="one">%d song found.</item> <!-- The example of %d is 0 --> <item quantity="zero">%d songs found. </item> <!-- The example of %d is 2 --> <item quantity="two">%d songs found.</item> <!-- The example of %d is 3 --> <item quantity="few">%d songs found.</item> <!-- The example of %d is 11 --> <item quantity="many">%d songs found.</item> <!-- The example of %d is 2.07--> <item quantity="other">%d songs found.</item> </plurals> |
注:虽然d%为整形,不可能为小数2.07,但是各国小数单复数表达可归为一类,所以以小数代表为其他情况
【情况二】含有变量的语句未使用两条单独的字串ID,通过代码分支区分单复数
步骤一:将两条代码分支合并,不采用if语句判断,统一使用同样的字串id,通过getQuantityString()方法加载。举例如下:
修改前:
int count = getNumberOfsongsAvailable(); Resources res = getResources(); if( count == 1 ) { String songsFound = res.getString(R.string. numberOfSongsAvailable_s, count); } else { String songsFound = res.getString(R.string. numberOfSongsAvailable_p, count); } |
修改后:
int count = getNumberOfsongsAvailable(); Resources res = getResources(); String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count,count); |
步骤二:见情况一中的步骤二和步骤三处理,需要将两条字串合为一条单独字串
修改前:
<string name="numberOfSongsAvailable_s">One song found.</ string > <string name="numberOfSongsAvailable_p">%d songs found.</ string > |
修改后:参考情况一步骤三修改样例
【情况三】含有变量的语句已经使用getQuantityString()方法支持单复数,但只有”one”和”others”两种quality的字串。举例如下:
<plurals name="numberOfSongsAvailable"> <item quantity="one">%d song found.</item> <item quantity="other">%d songs found.</item> </plurals> |
步骤:参考情况一中的步骤二和步骤三,将两条quality扩展成六条quality处理