Android数据绑定“??”来自资源的符号和参数化字符串。如何避免 'null' 文本?

Android DataBinding "??" notation and parametrized string from resources. How to avoid 'null' text?

我有一些TextView's in my App that is compounded by a key from strings.xml resource file and a parameter that is passed dynamically. I use Android Data Binding where the '??'表示法意味着它应该用空白字符串替换空值,如下例所示。 但是,当参数值为 null 直到 TextView 充满数据时,我们会看到类似 "null min" 的内容,而我希望它是:“min”。

<TextView
    android:id="@+id/text_runtime"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:padding="2dp"
    android:text="@{@string/min(vm.runtime) ?? ``}"
    tools:text="120 min" />

strings.xml中:

<string name="min">
    <xliff:g id="min">%d</xliff:g>
    min
</string>

您在字符串中使用了整数占位符 xliff:

<xliff:g id="min">%d</xliff:g>

并向那里传递一个空字符串。更改您的字符串 xliff 以使用字符串占位符:

<xliff:g id="min">%s</xliff:g>

并将 vm.runtime 转换为字符串。

vm.runtime 可能为空,但这可能是字符串格式的有效参数,因此它被认为是有效的,?? 永远不会被计算。

您可以使用的一个表达式是:

<TextView
    android:id="@+id/text_runtime"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:padding="2dp"
    android:text="@{vm.runtime == null ? `` : @string/min(vm.runtime)}"
    tools:text="120 min" />

如果你想让它有 min 而不是空字符串,你可以格式化字符串两次。

<TextView
    android:id="@+id/text_runtime"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:padding="2dp"
    android:text="@{@string/min(@string/quantity(vm.runtime) ?? ``)}"
    tools:text="120 min" />

你的最小值定义如下:

<string name="min">
    <xliff:g id="min">%s</xliff:g>
    min
</string>

数量字符串将是:

<string name="quantity">%d</string>

我认为这应该适用于所有语言,但如果您打算本地化,我建议使用复数而不是字符串。