Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in (android) xml resource android:text to have variable format float precision?

Having a text resource like this

<string name="list_item_station_detail_current_price_price_text">%1$.2f</string>

Used in a layout xml like this

android:text="@{@string/list_item_station_detail_current_price_price_text(currentPrice.price)}"

My trouble is that the precision isn't always 2 digits ( %1$.2f ), it may be variable. Is there a clever trick to fix this, maybe nested strings, or something ?

like image 793
Roar Grønmo Avatar asked Nov 17 '25 06:11

Roar Grønmo


1 Answers

Set up a string array where each entry represents a different precision.

<string-array name="list_item_station_detail_current_price_price_text">
    <item>%1$.2f</item>
    <item>%1$.3f</item>
    <item>%1$.4f</item>
</string-array>

In the XML, define the text for the TextView as follows:

   android:text="@{String.format(@stringArray/list_item_station_detail_current_price_price_text[currentPrice.precision],currentPrice.price)}"

I assume that you have or can create a variable with the precision.

Based upon the precision, the appropriate string is selected. (Precision of 2 maps to index 0, 3->1, 4->2) The price is the argument to the selected string.

like image 196
Cheticamp Avatar answered Nov 19 '25 20:11

Cheticamp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!