Android带参字串的写法注意事项

来源:互联网 发布:三国令神器进阶数据 编辑:程序博客网 时间:2024/06/05 22:57

问题引入

1.项目中会常常遇到一些带参数的字串。例如,Android原生系统中,当电量低于15%时,会提示“Battery is low”等信息,如下图所示。


2. 由于项目组自己有针对源码中的所有字串进行汇总,方便进行字串翻译库统一管理更新。但是期间出现一个问题,就是效果看起来少了个%。

[原始字串id]

S:SystemUI:battery_low_percent_format

[源码字串翻译]

<string name="battery_low_percent_format" msgid="2900940511201380775">"<xliff:g id="PERCENTAGE">%s</xliff:g> remaining"</string>

项目Java代码中访问方式如下:

    private void showWarningNotification() {        final int textRes = mSaver ? R.string.battery_low_percent_format_saver_started                : R.string.battery_low_percent_format;        //final String percentage = NumberFormat.getPercentInstance().format((double) mBatteryLevel / 100.0);//原生做法        final Notification.Builder nb = new Notification.Builder(mContext)                .setSmallIcon(R.drawable.ic_power_low)                // Bump the notification when the bucket dropped.                .setWhen(mBucketDroppedNegativeTimeMs)                .setShowWhen(false)                .setContentTitle(mContext.getString(R.string.battery_low_title))                .setContentText(mContext.getString(textRes, mBatteryLevel/*percentage*/))//modify by xxx for systemUI FC when battery is low at 2015 1116                .setOnlyAlertOnce(true)                .setDeleteIntent(pendingBroadcast(ACTION_DISMISSED_WARNING))                .setPriority(Notification.PRIORITY_MAX)                .setVisibility(Notification.VISIBILITY_PUBLIC)                .setColor(mContext.getColor(                        com.android.internal.R.color.battery_saver_mode_color));

3.从以上代码可知,是由于项目上对此作出了修改,原生使用percentage作为参数传给%s,而经过NumberFormat的处理,返回的直接时14%,所以原生机器Nexus不会存在这个问题。而我们直接传送的时一个整型数值,因而问题出现了。


问题处理

如果在不再修改Java代码的情况下,该如何调整字串翻译,才能使得这个%显现呢,这就涉及到%的添加和转义的问题。

经过自己写的一个小应用测试,得出如下结论:
1.首先我测试了4中情况的字串,定义如下:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"><string name="get_paired_bluetooth_device2">GET BLUETOOTH 100%</string>   ---->显示为GET BLUETOOTH 100%<string name="get_paired_bluetooth_device3">GET BLUETOOTH 100%%</string>   ---->显示为GET BLUETOOTH 100%%<string name="xdayi1"><xliff:g id="percentage">%s</xliff:g> %% remaining</string>  ---->显示为23 % remaining<!-- <string name="xdayi2"><xliff:g id="percentage">%s</xliff:g> % remaining</string> -->  ---->发生force close</resources>

2.
[结论] 
1.不包含<xliff:g>标签的字串,无论1个还是2个%,都不会发生force close,如果想表达34%,这只需一个%即可(这与之前验结果一致);
2.如果字串中包含<xliff:g>标签,不论是在<xliff:g>标签里面还是外面,如果想表达35%,必须包含两个%。因为只要字串中包含了<xliff:g>,该字串解析需要用到以下红色字体的命名空间。另外,无论<xliff:g>标签里面还是外面,使用一个%,都会发生force close。
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

[补充]
当然,后两个字串的%放置在标签里面,结果也是一样的。
<string name="xda1"><xliff:g id="percentage">%s%%</xliff:g> remaining 2</string>  OK<string name="xda2"><xliff:g id="percentage">%s%</xliff:g>remaining 2</string>  NOK(force close)

原始文档

本文个人原创原始文档获取地址如下,
http://download.csdn.net/detail/u013398960/9804976

0 0