且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java正常运行时,Kotlin在PasswordTransformationMethod中崩溃

更新时间:2023-09-18 23:45:22

幸运的是,Android/Kotlin允许在单个项目中混合Java和Kotlin文件.我用它来解决问题.

Fortunately, Android/Kotlin allows mixing Java and Kotlin files in a single project. I used this as a work around for the problem.

创建了一个用于处理密码的Java类.请注意,CharSequence在这里是本机Java类,这有所作为.

Created a Java class for the password handling. Please notice, CharSequence is a native Java class here, and this makes a difference.

import java.lang.CharSequence;

public class PasswordHandler implements CharSequence {

    private CharSequence mSource;
    private Switch mUnmask;

    public PasswordHandler(CharSequence source, Switch unmask) {
        mSource = source;
        mUnmask = unmask;
    }

    public char charAt(int index) {
        return mUnmask.isChecked()?mSource.charAt(index):'*';
    }
    public int length() {
        return mSource.length();
    }
    public CharSequence subSequence(int start, int end) {
        return mSource.subSequence(start, end);
    }

    @NonNull
    @Override
    public String toString() {
        String star = new String();
        int l = length();
        if (!mUnmask.isChecked()) {
            while (l-- > 0){
                star += "*";
            }
        }
        return mUnmask.isChecked()? mSource.toString():star;
    }
}

在Kotlin的类中的getTransfromation方法中实例化了该类. Kotlin编译器这次表现良好.崩溃不再发生了.我仍然希望看到纯Kotlin的解决方案.

Instantiated this class in getTransfromation method in a Kotlin's class. Kotlin compiler took it well this time. Crashes do not happen anymore.I still would like to see a pure Kotlin's solution for this.

mPwd!!.transformationMethod = object : PasswordTransformationMethod() {
            override fun getTransformation(source: CharSequence, view: View): CharSequence {
                return PasswordHandler(source, mChkUnmask)
            }

        }