安卓。文本输入布局。切换密码可见性事件侦听器?

Tim*_*ima 3 android android-textinputlayout

在 TextInputLayout 中有一个用于 InputType textPassword 的密码可见性切换按钮。

是否有可能以某种方式捕获切换事件?

我找不到任何公共方法

Tim*_*ima 6

我查看了 TextInputLayout 的源代码以找到切换按钮的视图类型。它的 CheckableImageButton。其他一切都很容易。您需要找到在 TextInputLayout 视图的子项上递归迭代的视图。然后按照@MikeM 在评论中的建议设置OnTouchListener。

View togglePasswordButton = findTogglePasswordButton(mTextInputLayoutView);
if (togglePasswordButton != null) {
    togglePasswordButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // implementation
            return false;
        }
    });
}

private View findTogglePasswordButton(ViewGroup viewGroup) {
    int childCount = viewGroup.getChildCount();
    for (int ind = 0; ind < childCount; ind++) {
        View child = viewGroup.getChildAt(ind);
        if (child instanceof ViewGroup) {
            View togglePasswordButton = findTogglePasswordButton((ViewGroup) child);
            if (togglePasswordButton != null) {
                return togglePasswordButton;
            }
        } else if (child instanceof CheckableImageButton) {
            return child;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

findTogglePasswordButton 的另一种实现

private View findTogglePasswordButton() {
    return findViewById(R.id.text_input_password_toggle);
}
Run Code Online (Sandbox Code Playgroud)

@迈克M。谢谢你的身份证