简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM