当我使用普通的editext编写此代码时,它可以正常工作,而当我不使用TextInputLayout / TextInputEditText时,它将无法工作。我想要的是输入字段(EditText)通过数据绑定观察字符串。
我尝试通过代码和xml来遵守它
XML
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/new_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/new_passwod"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="15dp"
app:passwordToggleEnabled="true"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:text="@={changePasswordViewModel.newPassword}"
app:onFocusChange="@{handler.newPasswordFocusChanged}"
app:onTextChange="@{handler.passwordTextChanged}"
/>
ViewModel
//Fields
val currentPassword = MutableLiveData<String>()
val newPassword = MutableLiveData<String>()
val confirmNewPassword = MutableLiveData<String>()
//Handler
inner class Handler {
val newPasswordFocusChanged = object : FocusChangedListener {
override fun focusChanged(hasFocus: Boolean) {
if (!hasFocus && !newPassword.value.validateRegex(accountFormConfiguration.getPasswordRegex())) {
_status.value = ModelEvent(ChangePasswordStatus.NewPasswordValidationError(errorMessage = accountFormConfiguration.getPasswordRegexError(), isErrorEnabled = true))
} else {
_status.value = ModelEvent(ChangePasswordStatus.NewPasswordValidationError(null, isErrorEnabled = false))
}
}
}
}
sealed class ChangePasswordStatus {
data class NewPasswordValidationError(val errorMessage: String?, val isErrorEnabled: Boolean) : ChangePasswordStatus()
data class ConfirmNewPasswordValidationError(val errorMessage: String) : ChangePasswordStatus()
data class SamePasswordValidationError(val errorMessage: String) : ChangePasswordStatus()
data class Failure(val errorMessage: String) : ChangePasswordStatus()
}
// BindinigAdapter
@BindingAdapter("app:onFocusChange")
fun onFocusChange(text: EditText, focusChangedListener: FocusChangedListener) {
text.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
focusChangedListener.focusChanged(hasFocus)
}
}
查看处理状态
private fun handleStatus(status: ChangePasswordStatus?) {
when(status) {
is ChangePasswordStatus.NewPasswordValidationError -> {
binding.newPassword.error = status.errorMessage
binding.newPassword.isErrorEnabled = status.isErrorEnabled
}
扩展功能
fun String?.validateRegex(regex: String?): Boolean {
if (this.isNullOrBlank() || regex.isNullOrBlank()) return false
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(this)
return matcher.matches()
}
答案 0 :(得分:0)
您是否在片段绑定中完成了setLifecycleOwner()?