我有一个包裹编辑文本的自定义视图。
我希望通过数据绑定在使用此自定义视图的类上观察此编辑文本的更改。
如何将编辑文本的输入字符串公开给使用自定义视图的其他类?
双向数据绑定是唯一方法吗?
在其他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}"/>
自定义视图的布局(线性布局):
<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>
如果要在示例(app:password="@=controller.password"
)中使用xml语法,则需要使用@BindingAdapter
和@InverseBindingAdapter
批注定义用于双向数据绑定的静态方法。您可以找到一个官方示例here(尽管我更喜欢使用顶级kotlin扩展功能,而不是将它们嵌套在object
中,因为它不需要@JvmStatic
注释并且感觉更惯用了)。您也可以查看库源文件,以了解如何为TextView
here定义2向绑定适配器,尽管它可能比案例中需要做的更多。
如果您只需要observe更改文本,而无需直接在自定义视图上设置文本,则不需要双向数据绑定,并且可以设置某种侦听器文本更改时回叫(如果有公共设置器,则可以通过数据绑定设置)或公开您可以观察到的LiveData<String>
(不使用xml /数据绑定)。
我可以想到两种方法来实现
@BindingAdapter(“ bind:doSomething”)有趣的bindDoSomething(查看:EditText,虚拟机:ViewModel?){vm?.let {view.addTextChangedListener(object:TextWatcher {{}重写fun afterTextChanged(s:是否可编辑?){}覆盖fun onTextChanged(s:CharSequence,开始:Int,之前:Int,count:Int){vm.callFun()}})}}
并且在您的xml中:
app:doSomething="@{vm}"
让我知道这是否有帮助或您有任何疑问