Dan*_*ker 5 data-binding android kotlin
我正在尝试在 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
<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)}"/>
Run Code Online (Sandbox Code Playgroud)
data class Product(
val height: Float?,
val length: Float?,
val width: Float?,
val weight: Float?,
): BaseObservable() {
Run Code Online (Sandbox Code Playgroud)
使用转换器类后,编译时出现以下错误:
error: cannot generate view binders java.lang.NullPointerException at android.databinding.tool.expr.Expr.lambda$join$0(Expr.java:771)
Run Code Online (Sandbox Code Playgroud)
感谢您的建议。问题出在我的模型中。我不得不将宽度属性从 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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1209 次 |
| 最近记录: |