TextInputLayout PasswordToggle - 处理单击事件

时间:2017-11-03 13:31:16

标签: android android-edittext android-textinputlayout

我的TextInputLayout PasswordToggle用于我的密码EditText,如下所示,

<android.support.design.widget.TextInputLayout
                        android:id="@+id/password_input_layout"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/text_input_height"
                        android:gravity="center"
                   app:passwordToggleDrawable="@drawable/password_visibility"
                        app:passwordToggleEnabled="true">

                        <android.support.v7.widget.AppCompatEditText
                            android:id="@+id/register_password_edittext"
                            android:layout_width="match_parent"                              
                    android:layout_height="@dimen/appcompat_editText_height"
                            android:hint="@string/register_password"
                            android:imeOptions="actionNext"
                            android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>

现在我还为此密码TextWatcher实施了EditText来处理这样的验证,

 passwordEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                // Do validation here.
            }
        });

问题是,当用户点击eye-icon TextInputLayout <{1}}我的TextChangeListener被无理由触发时,验证失败就会不必要地执行。

我该如何避免这种情况?如何处理PasswordToggleIcon点击操作?

1 个答案:

答案 0 :(得分:1)

        passwordEditText.addTextChangedListener(new TextWatcher() {
        String textBeforeChange;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            textBeforeChange = s.toString();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!textBeforeChange.equals(s.toString)) {
                // Do validation here.
            } 
        }
    });

如果文本没有改变,那么我想不需要进行预处理验证吗?可能我错过了你的问题的意图。干杯!