Duk*_*uke 51 android android-xml
我正在使用Plurals来简化我的代码.例如,我曾经有过
<string name="cat">Cat</string>
<string name="cats">Cats</string>
Run Code Online (Sandbox Code Playgroud)
我现在使用Plurals而不是多个字符串
<plurals name="cats">
<item quantity="one">Cat</item>
<item quantity="other">Cats</item>
</plurals>
Run Code Online (Sandbox Code Playgroud)
但是,我曾经检索过要在我的XML中用作标题或摘要的字符串.例如,
android:title="@string/cats"
Run Code Online (Sandbox Code Playgroud)
删除了该字符串以支持Plural,我现在不确定如何从XML中检索我的字符串.我做了一个天真的尝试
android:title="@plurals/cats"
Run Code Online (Sandbox Code Playgroud)
但这只是给了我@1234567890
而不是Cats
(或Cat
).
有人知道是否可以从XML中检索Plural中的字符串?
gwv*_*eri 56
你必须通过代码设置它:
...setText(yourContext.getResources().getQuantityString(R.plurals.cats, catsCountVar));
Run Code Online (Sandbox Code Playgroud)
And*_*ggs 12
现在可以使用数据绑定表达式在 XML 中完成此操作:
android:text="@{@plurals/cats(catCount)}"
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档中的此页面:https : //developer.android.com/topic/libraries/data-binding/expressions#resources
Cle*_*lin 10
您可以通过将字符串资源留在原始位置并在多个资源中引用它们来获得Plurals的运行时优势和字符串资源的静态优势.
来自https://developer.android.com/guide/topics/resources/string-resource.html#Plurals(强调添加).
<item>
复数或单数字符串.该值可以是对另一个字符串资源的引用.必须是元素的子元素.请注意,您必须转义撇号和引号.有关正确设置字符串样式和格式的信息,请参阅下面的格式和样式.例:
<string name="cat">Cat</string>
<string name="cats">Cats</string>
<plurals name="cats">
<item quantity="one">@string/cat</item>
<item quantity="other">@string/cats</item>
</plurals>
Run Code Online (Sandbox Code Playgroud)
现在您可以android:title="@string/cats"
在XML文件中使用并使用
getQuantityString(R.plurals.cats, numberOfCats)
Run Code Online (Sandbox Code Playgroud)
在运行时.
这现在可以从 xml 中实现。如果你有复数形式的参数,你必须记住两次传递数量变量。就像下面的例子一样。
<plurals name="number_of_students_in_topic">
<item quantity="zero">None are currently in this topic.</item>
<item quantity="one">One student is currently in this topic.</item>
<item quantity="other">%d students are currently in this topic.</item>
</plurals>
Run Code Online (Sandbox Code Playgroud)
在带有数据绑定的 xml 中。
android:text="@{@plurals/number_of_students_in_topic(count, count)}"
Run Code Online (Sandbox Code Playgroud)
这是因为,使用getResources().getQuantityString(int id, intquantity, Object... formatArgs)在代码中(在 *BindingImpl 类中)转换带参数的复数
第一个计数是选择正确的复数形式,第二个是使用正确的值格式化字符串。
如果您的字符串包含带有数字的字符串格式,那么您需要将整数变量发送两次,例如
字符串.xml
<resources>
<plurals name="numberOfMinute">
<item quantity="one">%d minute</item>
<item quantity="other">%d minutes</item>
</plurals>
</resources>
Run Code Online (Sandbox Code Playgroud)
在 Java 中
int min = getNumberOfMinute();
Resources res = getResources();
String formattedStr = res.getQuantityString(
R.plurals.numberOfMinute,
min,
min
); //this will return "20 minutes" or "1 minute" depending on variable
Run Code Online (Sandbox Code Playgroud)
科特林文件
resources.getQuantityString(
R.plurals.numberOfMinute, //plural from strings.xml file
min, //quantity
min //var arg
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19439 次 |
最近记录: |