如何在android中使用TransformationMethod

前端之家收集整理的这篇文章主要介绍了如何在android中使用TransformationMethod前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个接受密码的EditText.我想在输入字符后立即隐藏字符.所以,我使用了TransformationMethod.
我是新手,所以,我尝试了以下代码.
EditText editText = (EditText) findViewById(R.id.editText);
editText.setTransformationMethod(new PasswordTransformationMethod());


private class PasswordTransformationMethod extends Transformation implements TransformationMethod {

    @Override
    public CharSequence getTransformation(CharSequence source,View view) {
        return "/";
    }

    @Override
    public void onFocusChanged(View view,CharSequence source,boolean focused,int direction,Rect prevIoUslyFocusedRect) {
        source = getTransformation(source,view);
    }
}

然而,它抛出,

01-03 10:22:35.750: E/AndroidRuntime(2102): java.lang.IndexOutOfBoundsException

我错过了什么.任何帮助将不胜感激.

解决方法

上述方法有很多错误.

所以,我正在分享用于将密码转换为点的代码.

在这样的Java文件中创建一个单独的类,

public class MyPasswordTransformationMethod 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; 
        }

        public char charAt(int index) {
            return '.'; 
        }

        public int length() {
            return mSource.length(); 
        }

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

实现是这样的,

passwordEditText = (EditText) findViewById(R.id.passwordEditText);
passwordEditText.setTransformationMethod(new MyPasswordTransformationMethod());

猜你在找的Android相关文章