Search code examples
androidkotlinstring-formattingandroid-databinding

How does one convert an integer to a float while data binding?


I have an Int which contains a decimal number in units of tenths, so for example my int holds 308 to represent the decimal number 30.8. I want to use data binding to display this number in a TextView along with some other text. My TextView has the following text entry:

android:text="@{String.format("my value: %.1f", @{viewModel.myValue}.toFloat()/10.0f)}"

This fails to build with the following error:

[databinding] {"msg":"cannot find method toFloat() in class java.lang.Integer","file":"app/src/main/res/layout/fragment_you.xml","pos":[{"line0":163,"col0":54,"line1":163,"col1":84}]}

The value in question is defined like so:

private val _myValue = MutableLiveData<Int>()
val myValue: LiveData<Int> = _myValue

I thought this meant it was a Kotlin integer and i could call Kotlin functions on it, but apparently it's a java integer and I can't?

Why can't I call toFloat() there? How can I display this Int as a decimal number?


Solution

  • In xml if you want to use casting you will have to do it the way you do in JAVA

    Here to convert it to float try using ->

    android:text="@{String.format(&quot;my value: %.1f&quot;, Float.valueOf(@{viewModel.myValue})/10.0f)}"
    

    .toFloat is to be done in kotlin classes. In xml still you have to use JAVA