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

Time:12-22

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?

CodePudding user response:

I think, it will work.

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

CodePudding user response:

This might help you.

DataBindingConverter.kt

class DataBindingConverters {
    companion object {

        @JvmStatic
        fun convertIntegerToFloat(value: Int?): Float {
            return value/10.0f
        }

    }
}

XML import

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <import type="com.package.DataBindingConverter" />
    </data>
.....

Bind to View

<EditText
    ...
    android:text="@={DataBindingConverter.convertIntegerToFloat(viewModel.myValue)}" />
  • Related