Issue
I have some 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 '??' notation means it should replace nulls with blank strings, as example bellow shows.
But when the parameter value is null until the TextView
is full loaded with data we see something like "null min" when I like it to be: " 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" />
in strings.xml
:
<string name="min">
<xliff:g id="min">%d</xliff:g>
min
</string>
Solution
The vm.runtime
may be null, but that is possibly a valid parameter to a string format, so it is considered valid and the ??
won't ever be evaluated.
One expression you can use is:
<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" />
If you want it to have the min
instead of an empty string, you can format the string twice.
<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" />
And your min is defined like this:
<string name="min">
<xliff:g id="min">%s</xliff:g>
min
</string>
And the quantity string would be simply:
<string name="quantity">%d</string>
I think this should format properly in all languages, though I would recommend using plurals instead of string for min if you plan to localize.
Answered By - George Mount
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.