Oto obejście, którego używam, aby rozwiązać ten problem bez przełączania się na MessageFormat.
Najpierw wyodrębniam ciąg „zero” do własnego zasobu ciągu.
<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>
Następnie mam kilka wygodnych metod w moim własnym 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);
}
}
Teraz za każdym razem, gdy chcę użyć określonego ciągu dla ilości zerowej, wzywam:
String pluralString = ResourcesUtil.getQuantityStringZero(
getContext().getResources(),
R.plural.x_items,
R.string.x_items_zero,
quantity
);
Chciałbym, żeby było coś lepszego, ale przynajmniej załatwia to zadanie, zachowując czytelność XML zasobu ciągu.