【问题标题】:Android two-way databinding Float to EditTextAndroid 双向数据绑定 Float 到 EditText
【发布时间】:2019-12-24 14:05:36
【问题描述】:

我正在尝试在 EditText 上使用双向数据绑定。字符串值工作正常,但我无法让它为浮点值工作。

我尝试使用在此答案中找到的绑定适配器,但没有成功:Android DataBinding float to TextView

然后我在 android 开发者网站上找到了这个 Converter 类。 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() {

使用转换器类后,编译时出现以下错误:

error: cannot generate view binders java.lang.NullPointerException at android.databinding.tool.expr.Expr.lambda$join$0(Expr.java:771)

【问题讨论】:

  • 你在你的xml中导入了Converter类吗?在数据&lt;import type="yourpackage.Converter"/&gt;??
  • 是的,我已经导入了课程。当我从文本属性中删除 = 时,编译正在工作并且 edittext 具有模型中的数据。 android:text"@{Converter.floatToString(product.width)}"
  • 检查 null 然后转换。初次使用数据绑定时,它将为空。

标签: android kotlin data-binding


【解决方案1】:

感谢您的建议。问题出在我的模型中。我不得不将 width 属性从 val 更改为 var。 (val 属性不能重新分配。这些类似于 Java 中的 final 属性)

我没有使用 Converter 类,而是添加了 BindingAdapter。对我来说看起来更干净。

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());
    }
}

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多