android - BindingAdapter 弃用警告

标签 android android-databinding

我使用 BindingAdapter 来实现 TextInputLayout 字段的验证。我的对象有一个 ObservableBoolean 'valid',当更改时将执行我的绑定(bind)适配器来设置/清除字段上的错误消息。它工作得很好,但我现在看到以下警告并希望解决它:

Warning: Use of ObservableField and primitive cousins directly as method parameters is deprecated and support will be removed soon. Use the contents as parameters instead in method BindingUtils.setError

适配器:

@BindingAdapter({"error", "errorMsg"})
public static void setError(TextInputLayout view, ObservableBoolean isValid, String errorMsg){
    String errorString = isValid.get() ? null : errorMsg;
    view.setError(errorString);
}

以及绑定(bind)表达式:

    <android.support.design.widget.TextInputLayout
        app:error="@{viewModel.name.valid}"
        app:errorMsg="@{@string/template_details_error_name_required}"

为了解决该问题,我修改了适配器和绑定(bind)表达式,如下所示,但这导致了新的弃用警告:

Warning: Do not explicitly call 'get()' on ObservasbleFields in an expression. This support will be removed soon. 'viewModel.name.valid.get()'

修改后的适配器:

@BindingAdapter({"error", "errorMsg"})
public static void setError(TextInputLayout view, Boolean isValid, String errorMsg){

修改后的绑定(bind)表达式:

<android.support.design.widget.TextInputLayout
    app:error="@{viewModel.name.valid.get()}"
    app:errorMsg="@{@string/template_details_error_name_required}"

现在实现这一目标的推荐方法是什么?

此相关主题 Android Databinding BindingAdapter Error 询问 BindingAdapters 中的 Observables 是否有有效的用例。也许这就是其中之一。

最佳答案

您只需更改适配器本身。 ObservableBoolean 在布局中自动展开。

@BindingAdapter({"error", "errorMsg"})
public static void setError(TextInputLayout view, boolean isValid, String errorMsg){
    String errorString = isValid ? null : errorMsg;
    view.setError(errorString);
}

<android.support.design.widget.TextInputLayout
    app:error="@{viewModel.name.valid}"
    app:errorMsg="@{@string/template_details_error_name_required}"

但是您的属性名称和参数名称在语义上不匹配。

关于android - BindingAdapter 弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570882/

相关文章:

android - 如何保存和检索 Android 应用程序上次运行的数据?

android - 为什么我们在 OpenGL (ES) android 中以字节为单位分配 block 而不是 float ,尽管我们大部分时间都使用 float

android - 如何将光标定位到某个 EditText 框?

java - android数据绑定(bind)错误: cannot find symbol

子模块中的 Android 数据绑定(bind)

android - 如何列出android 10上的所有pdf文件?

android - 如何将 SearchWidget 添加到 ActionBar?

android - 我可以使用数据绑定(bind)将 UI 与我的 View 模型中的数据绑定(bind)吗?

java - MVVM + 数据绑定(bind) + View 模型不更新 View

java - Android Textview 中的条件字符串与未评估数据绑定(bind)