这是我用来处理此问题而不切换到MessageFormat的解决方法。

首先,我将“零”字符串提取到自己的字符串资源中。

No items.

@string/x_items_zero

One item.

%d items.

然后我在我自己的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清晰。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐