因此,如果用户输入" 1234",他们将在EditText字段中看到" 1234"。但是当该领域失去焦点时,我希望它显示" ****"
因此,我已经实现了一个自定义转换方法,该索引只有在EditText字段没有焦点的情况下才能掩盖输入的文本。
当我输入文本" 12345"时,它将其显示为" 12345",但是当我单击其他字段时,数字永远不会被掩盖。我想看" *****",但我仍然看到相同的" 12345"
,如果我旋转设备(强迫它重新加载所有内容),它正确显示了" *****"。而且,当我单击EditText字段时,它会正确地将蒙版的文本从" *****"更改为" 12345",因此在获得焦点时起作用,而在失去焦点时则不行。我已经尝试实现onfocuschangelistener,但似乎没有影响。
有什么办法可以强迫EditText字段在失去焦点时重新绘制文本?
设置:
editText.setTransformationMethod(CustomPasswordTransformationMethod(numUnobfuscatedDigits))
editText.setOnFocusChangeListener { view, hasFocus ->
((EditText)view).invalidate()
((EditText)view).refreshDrawableState()
custompasswordtransformationMethod: 公共类CustomPasswordTransFormationMethod扩展了密码TransFormationMethod { 私有int unopfustated = 1; 私人布尔不合时宜= 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());
}
}
});
也许您可以尝试保持简单:
String password = "";
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
editText.setText(password, TextView.BufferType.EDITABLE);
} else {
password = editText.getText().toString();
String ofuscated = "";
for (int i = 0; i < password.length(); i++){ ofuscated += "*"; }
editText.setText(ofuscated, TextView.BufferType.EDITABLE);
}
}
});