因此,如果用户输入“1234”,他们将在edittext字段中看到“1234”。但当那个区域失去焦点时,我希望它显示“***”
所以我实现了一个自定义的transformationmethod,它只在edittext字段没有焦点时屏蔽输入的文本。
当我输入文本“12345”时,它会显示它应该是“12345”,但当我单击其他字段时,数字永远不会被屏蔽。我想看“****”,但我仍然看到相同的“12345”
如果我旋转设备(强制它重新加载所有内容),它将正确显示“*****”。当我点击EditText字段时,它会正确地将屏蔽文本从“****”更改为“12345”,这样它在获得焦点时工作,但在失去焦点时不工作。我试过实现一个onfocuschangelister,但它似乎没有任何影响。
有什么方法可以在EditText字段失去焦点时强制它重新绘制文本吗?
设置:

 editText.setTransformationMethod(CustomPasswordTransformationMethod(numUnobfuscatedDigits))
editText.setOnFocusChangeListener { view, hasFocus ->
                    ((EditText)view).invalidate()
                     ((EditText)view).refreshDrawableState()

自定义密码转换方法:
公共类customPasswordTransformationMethod扩展了PasswordTransformationMethod{
private int unobfuscated=1;
private boolean misfocused=false;
    /**
     * @param number the number of digits that will be unObfuscated at the end of the input string. Must be a positive integer or 0.
     */
    public CustomPasswordTransformationMethod(int number) {
        if (number < 0) {
            Log.e(TAG, "Invalid parameter number =" + number + " number of un-obfuscated digits must be a positive integer or 0.");
            unObfuscated = 0;
        }
        unObfuscated = number;
    }

    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return new PasswordCharSequence(source);
    }

    @Override
    public void onFocusChanged(View view, CharSequence sourceText,
                               boolean focused, int direction,
                               Rect previouslyFocusedRect) {
        super.onFocusChanged(view,sourceText,focused, direction, previouslyFocusedRect);
        mIsFocused = focused;
    }


    private class PasswordCharSequence implements CharSequence {
        private CharSequence mSource;

        public PasswordCharSequence(CharSequence source) {
            mSource = source; // Store char sequence
        }

        public char charAt(int index) {
            if(mIsFocused) return mSource.charAt(index);
            else {
                if (index < ((length()) - unObfuscated)) return '●';
                return mSource.charAt(index);
            }
        }

        public int length() {
            return mSource.length(); // Return default
        }

        public CharSequence subSequence(int start, int end) {
            return mSource.subSequence(start, end); // Return default
        }
    }
};

最佳答案

试试这个看看它是否能满足你的需要。

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if(hasFocus){
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
        else{
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }
});

关于android - 如何在 View 失去焦点时屏蔽EditText中的文本。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46574752/

10-08 23:53