Android_EditText 密码框默认是小圆点 怎么改成其它的(*)?

text.setTransformationMethod(new AsteriskPasswordTransformationMethod());
 
 
public class AsteriskPasswordTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
    return new PasswordCharSequence(source);
}
 
private class PasswordCharSequence implements CharSequence {
    private CharSequence mSource;
    public PasswordCharSequence(CharSequence source) {
        mSource = source; // Store char sequence
    }
    public char charAt(int index) {
        return '*'; // This is the important part
    }
    public int length() {
        return mSource.length(); // Return default
    }
    public CharSequence subSequence(int start, int end) {
        return mSource.subSequence(start, end); // Return default
    }
}

TextView : setInputType(). setTransformationMethod()

某些场合,可能需要在运行时令某个 TextView (可能是运行时创建的,也可以是写在 XML 文件中的)。由于无法通过 XML 文件指定其为 password 输入属性,那么如何实现这个效果呢?

TextView 有两个方法:

setInputType(int)
setTransformationMethod(TransformationMethod)

  

其中 setInputType 可以更改 TextView 的输入方式:Contact、Email、Date、Time、Short Message、Normal Text、Password 等。还可以指定各种更正选项,如 单词首字母大写、句子首字母大写、自动更正等。

使用方法:

int inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
                      | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
                      | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE;
       textView.setInputType(inputType);

而 setTransformationMethod 则可以支持将输入的字符转换,包括清除换行符、转换为掩码。使用方法:

 textView.setTransformationMethod(PasswordTransformationMethod.getInstance());

综合来说,如果需要实现自己的转换,可以通过实现 TransformationMethod 接口来达到你的目的(比如让输入的所有字符都变成 a,或者输入 a 显示 z,输入 z 显示 a 等)。

posted on 2014-11-20 12:35  坚持努力  阅读(452)  评论(0编辑  收藏  举报

导航