带空检查的双向绑定

Khe*_*raj 0 data-binding android android-databinding

在数据绑定适配器中,我想检查int模型中的值是否不为零。因为从不显示提示,如果默认值为 0,则 0 显示为文本。如果值为零,我想显示提示。

下面无需检查 0 int 值即可正常工作

   <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/port"
                android:inputType="number"
                android:text="@={`` + item.port}"
                />
Run Code Online (Sandbox Code Playgroud)

我试过这个不起作用

   <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/port"
                android:inputType="number"
                android:text='@={item.port != 0 ? `` + item.port : ""}'
                />
Run Code Online (Sandbox Code Playgroud)

item.portint价值

有什么建议可以只使用数据绑定来完成这项工作吗?

Geo*_*unt 5

我认为您需要一种BindingAdapter/InverseBindingAdapter或一种转换方法。最简单的可能是一种转换方法:

<layout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <data>
        <import type="com.example.mount.teststuff.Conversion"/>
        <variable name="port" type="int"/>
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <EditText
            android:id="@+id/input"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@={Conversion.intToString(port, port)}"
            android:textSize="40sp"/>
        <TextView
            android:id="@+id/output"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`` + port}"
            android:textSize="40sp"/>
    </LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)

在你的 Conversion 类中,你会有这样的东西:

public class Conversion {
    @InverseMethod("stringToInt")
    public static String intToString(int oldValue, int value) {
        if (value == 0) {
            return null;
        }
        return String.valueOf(value);
    }

    public static int stringToInt(int oldValue, String value) {
        if (value == null || value.isEmpty()) {
            return 0;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return oldValue;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我刚刚更新了答案以包含我测试过的布局和代码。您可以在此博客文章中查找更多详细信息