繁体   English   中英

带有 void 参数的 Android 数据绑定属性

[英]Android Data Binding attribute with void argument

我为数据绑定创建了一个自定义属性,它不需要任何参数,它所做的只是验证 TextinputEditText 的有效性,但我无法找到在 xml 属性中传递 void 参数的方法。

这不编译。

绑定适配器.java

@BindingAdapter("app:validator")
public static void textValidator(TextInputLayout textInputLayout) {

        doesSomething();
}

布局文件.xml

              <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:validator="@{ void }">

                 <android.support.design.widget.TextInputEditText
                        android:id="@+id/edit_text"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"" />

                </android.support.design.widget.TextInputLayout>

我试过在 xml 中传递 void 或 null ,但它只是不编译。 我研究发现方法中至少应该有一个或两个值参数。 所以我可以通过传递一个参数来让它工作,让我们说一个布尔值只是为了传递而不是使用它。 例如,

这个编译。 但这只是一个黑客,有人请提出更好的方法。

绑定适配器.java

@BindingAdapter("app:validator")
public static void textValidator(TextInputLayout textInputLayout, boolean bl) {

        doesSomething();
}

布局文件.xml

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:validator="@{ booleanVariable }">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/edit_text"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"" />

                </android.support.design.widget.TextInputLayout>

但这只是一个黑客,有人请提出更好的方法。

没有更好的方法,因为这不是数据绑定的目的。 它的目的是从字面上绑定 data ,这意味着应该有一些数据(一个参数)你想在你的视图上设置,而不必在你的代码中手动设置。

您尝试执行的操作实际上没有意义,因为您的自定义绑定只会在您传递要绑定到给定视图的数据时进行评估。 所以你最终会得到传递一些虚拟值来触发验证的代码,此时你也可以自己手动触发验证,这比通过这样的数据绑定间接执行要清晰得多。

如果您想验证您的视图以响应另一个视图上的某个事件,例如“提交按钮”单击或其他内容,那么您可以将事件处理程序绑定到控件,该控件又会调用您的doesSomething()方法。 请参阅数据绑定文档中有关事件处理部分

希望有帮助。

您可以传递验证标准,例如一个枚举,指示是否必须验证电子邮件、数字、最小长度字符串等,甚至是错误消息:

@BindingAdapter({"app:validation", "app:errorMsg"})
    public static void setErrorEnable(EditText editText, StringValidationRules.StringRule stringRule, final String errorMsg)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM