Android 数据绑定 - 观察包装在自定义视图中的编辑文本值

RoR*_*oob 7 android android-databinding

我有一个包含编辑文本的自定义视图。

我希望使用数据绑定在使用此自定义视图的类中观察此编辑文本的更改。

如何将编辑文本的输入字符串公开给使用自定义视图的其他类?

双向数据绑定是唯一的方法吗?

在其他 XML 中:

<MyCustomView
        android:id="@+id/password_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:password="@={controller.password}"
        app:isPasswordValid="@={controller.isValid}"/>
Run Code Online (Sandbox Code Playgroud)

自定义视图的布局(Linear Layout):

<merge>

    <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/security_code_input_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/email_text_view">

        <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/security_code_edit_text"
                android:background="@drawable/edittext_background"
                android:inputType="textPassword"
                android:text="@={view.pass}"
                app:onSubmit="@{() -> view.onKeyboardActionDoneClicked()}" />

    </com.google.android.material.textfield.TextInputLayout>

    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/textfield_error_invalid_password_length"
            app:visibleOrGone="@{view.showInvalidPasswordText}" />

</merge>
Run Code Online (Sandbox Code Playgroud)

小智 5

如果要在示例 ( app:password="@=controller.password") 中使用 xml 语法,则需要为 2 路数据绑定 with@BindingAdapter@InverseBindingAdapterannotations定义静态方法。您可以在此处找到官方示例(尽管我更喜欢使用顶级 kotlin 扩展函数而不是将它们嵌套在 an 中,object因为它不需要@JvmStatic注释并且感觉更惯用)。您还可以查看库源,了解如何为TextView 此处定义 2 路绑定适配器,尽管它可能比您需要为您的案例做的更多。

如果您需要做的只是观察文本更改并且不需要直接在自定义视图上设置文本,那么 2 路数据绑定是不必要的,您可以设置某种侦听器,当文本更改时会回调(如果您有公共设置器,则可以通过数据绑定进行设置)或公开LiveData<String>您可以观察到的(不使用 xml/数据绑定)。