[英]Android two-way databinding Float to EditText
我正在嘗試在 EditText 上使用雙向數據綁定。 字符串值工作正常,但我無法讓它用於 Float 值。
我嘗試使用我在這個答案中找到的綁定適配器,但沒有成功: 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)
感謝您的建議。 問題出在我的模型中。 我不得不將寬度屬性從 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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.