Search code examples
androiddoubletwo-way-bindingkotlin-android

Two Way Binding on Double Android


I read a few posts to convert from String to Integer and tried to do the same to convert string to double using two-way binding but was unable to do it.

SampleViewModel.kt

class SampleViewModel: ViewModel() {

    val weight = MutableLiveData<Double>()

    fun validateFields() {
        Log.i("SAMPLE_VIEW_MODEL", "validateFields: ${weight.value}")
    }
}

TypeConverters.kt

object TypeConverters {

    @InverseMethod("stringToDouble")
    @JvmStatic
    fun doubleToString(value: Double?): String {
        return value?.toString() ?: ""
    }

    @JvmStatic
    fun stringToDouble(value: String): Double? {
        if (TextUtils.isEmpty(value)) {
            return null
        }
        return value.toDoubleOrNull()
    }
}

fragment_sample.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <variable
            name="viewModel"
            type="com.example.sampleapp.SampleViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout

        ...

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_weight"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/_10sdp"
            android:hint="@string/hint_weight"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="@+id/tilName">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/tiet_weight"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="numberDecimal"
                android:text="@={TypeConverters.doubleToString(viewModel.weight)}"/>

        </com.google.android.material.textfield.TextInputLayout>

        ...

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

The example above does not let me enter the proper value on UI like "56.78". I tried to follow this post but doesn't work for me. Another way is to take string value and then convert it into double and vice versa accordingly. I would like to know which is the correct way.


Solution

  • In your TextInputEditText, update this line

    android:text="@={String.valueOf(viewModel.weight)}"
    

    See Results

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/tiet_weight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:text="@={String.valueOf(viewModel.weight)}"/>