背景
需要实现一个 号码脱敏的EditText,在编辑时动态脱敏。该功能可以用 TransformationMethod
实现
TransformationMethod 使用注意点
public interface TransformationMethod
{
/**
* Returns a CharSequence that is a transformation of the source text --
* for example, replacing each character with a dot in a password field.
* Beware that the returned text must be exactly the same length as
* the source text, and that if the source text is Editable, the returned
* text must mirror it dynamically instead of doing a one-time copy.
* The method should not return {@code null} unless {@code source}
* is {@code null}.
*/
public CharSequence getTransformation(CharSequence source, View view);
/**
* This method is called when the TextView that uses this
* TransformationMethod gains or loses focus.
*/
public void onFocusChanged(View view, CharSequence sourceText,
boolean focused, int direction,
Rect previouslyFocusedRect);
}
TransformationMethod
方法用于转换TextView 的显示,需要注意的一点,转换后的长度必须与 source 长度相等.,如果长度不等,会在绘制Text时崩溃情况。
java.lang.IndexOutOfBoundsException
at android.view.GLES20Canvas.drawText(GLES20Canvas.java:888)
at android.text.Layout.drawText(Layout.java:367)
at android.widget.Editor.drawHardwareAccelerated(Editor.java:1514)
at android.widget.Editor.onDraw(Editor.java:1439)
at android.widget.TextView.onDraw(TextView.java:5780)
at android.view.View.draw(View.java:15488)
at android.view.View.updateDisplayListIfDirty(View.java:14377)