android – 使用TextInputLayouts passwordToggleEnabled的可见密码

我正在使用TextInputLayout和支持库中的新函数:passwordToggleEnabled.这给了一个很好的“眼睛” – 图标,让用户可以打开和关闭密码可见性.

我的问题是,是否有办法使用此功能,但开始密码可见?

我的xml:

<android.support.design.widget.TextInputLayout
                    android:id="@+id/password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:passwordToggleEnabled="true">

                    <EditText
                        android:id="@+id/password_edit"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/prompt_password"
                        android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>

切换看起来与此类似:

我还没有找到一种方法在xml中执行此操作,而不是在呈现视图后手动切换可见性的方法.如果我将EditText的输入类型设置为textVisiblePassword,则不会显示切换.如果我在代码中使用例如mPasswordEditText.setTransformationMethod(null);显示密码但切换消失,用户无法再次隐藏密码.我知道我可以手动完成所有操作,但只是想知道我是否可以使用新的魔术切换工作

解决方法

其中一种方法是,我们可以从TextInputLayout中搜索CheckableImageButton,然后根据EditText的密码可见性状态以编程方式对其执行onClick.

这是代码片段.

private CheckableImageButton findCheckableImageButton(View view) {
    if (view instanceof CheckableImageButton) {
        return (CheckableImageButton)view;
    }

    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        for (int i = 0,ei = viewGroup.getChildCount(); i < ei; i++) {
            CheckableImageButton checkableImageButton = findCheckableImageButton(viewGroup.getChildAt(i));
            if (checkableImageButton != null) {
                return checkableImageButton;
            }
        }
    }

    return null;
}

//...

if (passwordEditText.getTransformationMethod() != null) {
    CheckableImageButton checkableImageButton = findCheckableImageButton(passwordTextInputLayout);
    if (checkableImageButton != null) {
        // Make password visible.
        checkableImageButton.performClick();
    }
}

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...