The*_*his 17 android android-layout android-databinding
我想直接将错误消息绑定到android.support.design.widget.TextInputLayout
.我找不到通过布局设置错误的方法.这甚至可能吗?
这就是我想象的工作方式:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.view.View" />
<variable
name="error"
type="String" />
</data>
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true"
app:errorText="@{error}">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/username"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
</android.support.v7.widget.LinearLayoutCompat>
</layout>
Run Code Online (Sandbox Code Playgroud)
Mar*_*ski 39
在编写此答案时,没有与setError()
方法对应的XML属性,因此您无法直接在XML中设置错误消息,这有点奇怪errorEnabled
.但是,通过创建可以填补空白并提供缺失实现的Binding Adapter,可以轻松解决这个问题.像这样的东西:
@BindingAdapter("app:errorText")
public static void setErrorMessage(TextInputLayout view, String errorMessage) {
view.setError(errorMessage);
}
Run Code Online (Sandbox Code Playgroud)
请参阅官方绑定文档,"属性设置器"部分,尤其是"自定义设置器".
编辑
可能是愚蠢的问题,但我应该把它放在哪里?我是否需要扩展
TextInputLayout
并将其放入其中?
这根本不是一个愚蠢的问题,仅仅是因为你无法通过阅读官方文档得到完整的答案.幸运的是,它非常简单:您不需要扩展任何东西 - 只需将该方法放在项目的任何位置即可.您可以创建单独的类(即DataBindingAdapters
)或仅将此方法添加到项目中的任何现有类 - 这并不重要.只要您使用此方法注释@BindingAdapter
,确保它是,public
并且 static
它所在的类并不重要.
归档时间: |
|
查看次数: |
9705 次 |
最近记录: |