Reputation: 131
I am trying to use two-way databinding on a EditText. String values are working fine but I can't get it working for Float values.
I have tried to use a binding adapter that I found in this answer with no luck: Android DataBinding float to TextView
Then I found this Converter class on the android developers website. https://developer.android.com/topic/libraries/data-binding/two-way#kotlin
public class Converter {
@InverseMethod("stringToFloat")
public static String floatToString(float value) {
try {
return String.valueOf(value);
} catch (Exception e) {
return "";
}
}
public static float stringToFloat(String value) {
try {
return Float.parseFloat(value);
} catch (Exception e) {
return 0.0f;
}
}
}
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/width"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Width"
android:inputType="number"
android:text="@={Converter.floatToString(product.width)}"/>
data class Product(
val height: Float?,
val length: Float?,
val width: Float?,
val weight: Float?,
): BaseObservable() {
After using the converter class I get the following error when compiling:
error: cannot generate view binders java.lang.NullPointerException at android.databinding.tool.expr.Expr.lambda$join$0(Expr.java:771)
Upvotes: 6
Views: 2052
Reputation: 131
Thanks for the suggestions. The problem was in my model. I had to change the width property from val to var. (val properties cannot be reassigned. These are like final properties in Java)
And instead of using a Converter class I have added a BindingAdapter. Looks more clean for me.
public class TextViewBindingAdapter {
@BindingAdapter("android:text")
public static void setText(TextView view, Float value) {
if (value == null)
return;
view.setText(String.valueOf(value));
}
@InverseBindingAdapter(attribute = "android:text", event = "android:textAttrChanged")
public static Float getTextString(TextView view) {
return Float.valueOf(view.getText().toString());
}
}
Upvotes: 7