因此,如果用户输入“1234”,他们将在EditText字段中看到“1234”。但是当那个领域失去焦点时,我希望它显示“****”
所以我实现了一个自定义TransformationMethod,如果EditText字段没有焦点,它只会屏蔽输入的文本。
当我输入文本“12345”时,它显示为“12345”,但是当我点击不同的字段时,数字永远不会被屏蔽。我想看“*****”,但我仍然看到相同的“12345”
如果我旋转设备(强制它重新加载所有东西),它会正确显示“*****”。当我点击EditText字段时,它会正确地将屏蔽文本从“*****”更改为“12345”因此,在获得焦点时它会起作用,但在失去焦点时则不起作用。我试过实现一个OnFocusChangeListener,但似乎没有任何影响。
有什么办法可以强制EditText字段在失去焦点时重绘文字?
设定:
editText.setTransformationMethod(CustomPasswordTransformationMethod(numUnobfuscatedDigits))
editText.setOnFocusChangeListener { view, hasFocus ->
((EditText)view).invalidate()
((EditText)view).refreshDrawableState()
CustomPasswordTransformationMethod: public class CustomPasswordTransformationMethod extends 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
}
}
};
答案 0 :(得分:1)
试试这个,看看它是否能满足您的需求。
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus){
editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
else{
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
答案 1 :(得分:0)
也许你可以尝试保持简单:
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);
}
}
});