我只是在我的项目中玩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()
,也不
知道如何在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
时出现问题
答案 0 :(得分:3)
因此看起来不仅仅是我的问题,TextWatcher
在转换时会挂起。它每次都停止响应。我的问题是,我无法使用Kotlins String.replace()
解决方案只是使用适当版本的Kotlin
带有kotlin_version = '1.1.3-2'
答案 1 :(得分:1)
我刚尝试将您的代码转换为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)
}
}