在 Android 6.0 中设置错误后无法编辑 TextInputEditText

Cannot edit a TextInputEditText after setting an error on it in Android 6.0

我的布局中有一堆 TextInputEditText,其定义如下:

<android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

   <android.support.design.widget.TextInputEditText
                android:id="@+id/confirmPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/registration_confirm_password"
                android:inputType="textPassword" />

</android.support.design.widget.TextInputLayout>

当用户尝试提交表单时,我有一个验证方法来检查每个字段并在无效字段上设置错误,如下所示:

if(confirmPassword.text.toString() != password.text.toString()) {
        confirmPassword.error = "Passwords don't match"
        confirmPassword.setOnKeyListener { _, _, _ ->
            confirmPassword.error = null
            true
        }
        valid = false
}

一旦用户开始纠正错误,OnKeyListener 就会消除错误。

此代码在我的模拟器和装有 Android 5.1.1 的设备上完美运行。但是在我的一个用户的设备上,三星 Galaxy S6 Edge Android 6.0,当他犯了一个错误并且一个字段有错误时,他不能再编辑它了。

我是不是用错了TextInputEditText?这是一个已知的错误吗?有解决方法吗?

onKey is Called when a hardware key is dispatched to a view. This allows listeners to get a chance to respond before the target view.

Key presses in software keyboards will generally NOT trigger this method, although some may elect to do so in some situations. Do not assume a software input method has to be key-based; even if it is, it may use key presses in a different way than you expect, so there is no way to reliably catch soft input key presses.

return True if the listener has consumed the event, false otherwise.

当您从 setOnKeyListener 中的 onKey 方法 return true 消费事件时,事件将不会始终发送到视图 return false 如果您希望视图以默认方式对按键做出反应,则从中获取

但对您来说更好的解决方案是使用 addTextChangedListener 而不是 setOnKeyListener 这样您的代码可以更好地支持软键盘按键:

if(confirmPassword.text.toString() != password.text.toString()) {
            confirmPassword.error = "Passwords don't match"
            confirmPassword.addTextChangedListener (new TextWatcher {
                afterTextChanged(Editable s) { 
                    // Nothing to do here 
                }

                beforeTextChanged(CharSequence s, int start, int count, int after) { 
                   // Nothing to do here 
                }

                onTextChanged(CharSequence s, int start, int before, int count) {
                    // When user start to edit, delete the error feedback 
                    confirmPassword.error = null
                }
            });

    valid = false;          
}

View.OnKeyListener official doc所述:

Interface definition for a callback to be invoked when a hardware key event is dispatched to this view. The callback will be invoked before the key event is given to the view. This is only useful for hardware keyboards; a software input method has no obligation to trigger this listener.