根据其他视图的属性启用视图-android databinding

问题描述

我有一个TextInputLayout,其错误已启用,并且根据某些原因,错误被禁用。问题是我禁用了一个按钮,但是当另一个视图的错误消失时我想启用它。您知道使用数据绑定的工作原理吗?谢谢。我的代码是此代码,但是对错误启用/禁用更改没有反应。

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/layout1"
            app:errorTextAppearance="@style/errorText"
            app:errorEnabled="true"
            style="@style/outlinedTextInputLayout.Dense">
            
            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/name"
                style="@style/outlinedTextInputEditText.Multilines"
                android:hint="@string/name"
                android:text="@={viewModel.name}"/>

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

            <com.google.android.material.button.MaterialButton
                android:id="@+id/acceptBtn"
                android:onClick="@{() -> viewModel.accept()}"
                android:enabled="@{!name.isErrorEnabled()}"
                style="@style/materialButton.Text"
                android:text="@string/str_accept" />

解决方法

如果我理解正确,那么您希望基于文本更改启用或禁用按钮,如果是,则执行以下操作。

创建绑定适配器以设置像这样的文本观察器。

    @BindingAdapter("textChangedListener")
    @JvmStatic
    fun addOnTextChangedListener(textView: TextInputEditText,listener: TextWatcher) {
        autoCompleteTextView.addTextChangedListener(listener)
    }

秒,在这样的布局中传递侦听器。 app:addTextChangedListener="@{viewModel.nameWatcher}"

      <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/layout1"
        app:errorTextAppearance="@style/errorText"
        app:errorEnabled="true"
        style="@style/outlinedTextInputLayout.Dense">
        
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/name"
            style="@style/outlinedTextInputEditText.Multilines"
            android:hint="@string/name"
            app:addTextChangedListener="@{viewModel.nameWatcher}"
            android:text="@={viewModel.name}"/>

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

在您的视图模型中创建文本观察器,并在文本更改后立即检查文本有效性,并使用某些 MutableLiveData ObservableBoolean

启用和禁用按钮
val nameWatcher = object :TextWatcher {
  override fun afterTextChanged(s: Editable?) {
    //here change button enable disable using some mutable live data or observable boolean
  }

  override fun beforeTextChanged(s: CharSequence?,start: Int,count: Int,after: Int) {}

  override fun onTextChanged(s: CharSequence?,before: Int,count: Int) {}

}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...