android 中的两种数据绑定
Two way databindning in android
假设我有一个登录表单,等待用户输入 10 位数字 phone 号码,然后它会更改下一个按钮的可见性
我怎样才能在 XML 中实现这一点而无需代码?
这是 phone 检查功能:
fun EditText.isValidPhone() = this.text.length == 10
和布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<EditText
android:id="@+id/phoneEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:background="@null"
android:focusableInTouchMode="true"
android:hint="@string/mobile_phone"
android:inputType="number"
android:maxLength="10"
android:textColor="@color/regular_text"
android:textColorHint="@color/hint"
android:textSize="24sp" />
<TextView
android:id="@+id/authorization_next"
style="@style/accept_button"
android:text="@string/next"
android:visibility="gone" />
</LinearLayout>
生成的数据绑定 Java class 不知道扩展方法,因此您必须导入适当的 class 持有静态扩展方法。假设文件名为 extensions.kt,此 class 名称将为 ExtensionsKt
此外,您还必须将 View
导入到您的绑定中。您可以使用 onTextChanged
属性定义文本更改的回调和条件。
android:onTextChanged="@{(text, start, before, count) -> authorizationNext.setVisibility(ExtensionsKt.isValidPhone(phoneEdit) ? View.VISIBLE : View.GONE)}" />
也许只为 CharSequence
定义一个扩展名会很有用
fun CharSequence.isValidPhone() = length == 10
并将其用作 ExtensionsKt.isValidPhone(text)
。
假设我有一个登录表单,等待用户输入 10 位数字 phone 号码,然后它会更改下一个按钮的可见性 我怎样才能在 XML 中实现这一点而无需代码? 这是 phone 检查功能:
fun EditText.isValidPhone() = this.text.length == 10
和布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<EditText
android:id="@+id/phoneEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:background="@null"
android:focusableInTouchMode="true"
android:hint="@string/mobile_phone"
android:inputType="number"
android:maxLength="10"
android:textColor="@color/regular_text"
android:textColorHint="@color/hint"
android:textSize="24sp" />
<TextView
android:id="@+id/authorization_next"
style="@style/accept_button"
android:text="@string/next"
android:visibility="gone" />
</LinearLayout>
生成的数据绑定 Java class 不知道扩展方法,因此您必须导入适当的 class 持有静态扩展方法。假设文件名为 extensions.kt,此 class 名称将为 ExtensionsKt
此外,您还必须将 View
导入到您的绑定中。您可以使用 onTextChanged
属性定义文本更改的回调和条件。
android:onTextChanged="@{(text, start, before, count) -> authorizationNext.setVisibility(ExtensionsKt.isValidPhone(phoneEdit) ? View.VISIBLE : View.GONE)}" />
也许只为 CharSequence
定义一个扩展名会很有用
fun CharSequence.isValidPhone() = length == 10
并将其用作 ExtensionsKt.isValidPhone(text)
。