我使用以下方法来处理这个问题,而无需切换到MessageFormat。
首先,我将“零”字符串提取为自己的字符串资源。
<string name="x_items_zero">No items.</string>
<plurals name="x_items">
<!
<item quantity="zero">@string/x_items_zero</item>
<item quantity="one">One item.</item>
<item quantity="other">%d items.</item>
</plurals>
那么我在自己的ResourcesUtil中有一些便利方法
public static String getQuantityStringZero(Resources resources, int resId, int zeroResId, int quantity) {
if (quantity == 0) {
return resources.getString(zeroResId);
} else {
return resources.getQuantityString(resId, quantity, quantity);
}
}
public static String getQuantityStringZero(Resources resources, int resId, int zeroResId, int quantity, Object... formatArgs) {
if (quantity == 0) {
return resources.getString(zeroResId);
} else {
return resources.getQuantityString(resId, quantity, formatArgs);
}
}
现在,每当我想使用特定的零数量字符串时,我会调用:
String pluralString = ResourcesUtil.getQuantityStringZero(
getContext().getResources(),
R.plural.x_items,
R.string.x_items_zero,
quantity
);
我希望有更好的方法,但最起码这种方法可以完成任务,并且保持字符串资源XML的清晰可读性。