Kotlin和Android TextWatcher具有CharSequence / String替换功能

我只是在我的项目上玩Kotlin,我来到奇怪的问题…当试图转换自定义EditText Android工作室停止响应。 当我试图转换它的一部分,它转换这段代码时停止响应:

 private TextWatcher editor = new TextWatcher() { long newMicro = 0; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { s = s.toString().replace(".", "") .replace(",", "") .replace("$", ""); try { newMicro = Long.parseLong(s.toString()); } catch (Exception e) { newMicro = 0; } } @Override public void afterTextChanged(Editable editable) { removeTextChangedListener(editor); setMicroUnits(newMicro); addTextChangedListener(editor); } }; 

你有没有经历过这样的行为? 我无法在Kotlin中重新实现这个TextWatcher ,因为我不能执行任何操作

CharSequence.toString().replace()

也不

CharSequence.replace()

任何想法如何在Kotlin中实现自定义的TextWatcher? 这是我准备好的代码:

 val editor = object : TextWatcher { override fun afterTextChanged(p0: Editable?) { } override fun beforeTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) { } } 

编辑:在Android Studio 3预览版6上使用kotlin版本1.1.2-4时发生问题

我刚刚尝试在Android Studio中将您的代码转换为Kotlin,并将其挂起。 我认为这是TextWatcher接口方法中可空参数的问题。

无论如何,这段代码必须是你正在寻找的:

 private val editor = object : TextWatcher { var newMicro: Long = 0 override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val text = s.toString().replace(".", "") .replace(",", "") .replace("$", "") try { newMicro = java.lang.Long.parseLong(text) } catch (e: Exception) { newMicro = 0 } } override fun afterTextChanged(s: Editable?) { removeTextChangedListener(this) setMicroUnits(newMicro) addTextChangedListener(this) } } 

所以它看起来不仅是我的问题, TextWatcher在转换时挂起。 它每次都停止响应。 我的问题是,我无法使用Kotlins String.replace()

解决方案只是使用适当版本的Kotlin AndroidStudio 3.0预览版6与kotlin_version = '1.1.3-2'