Kotlin中点击按钮清空EditText提示类型不匹配如何解决
错误原因
Kotlin 中 EditText 的 text 属性对应类型为 Editable,而非 String 类型,直接赋值字符串会触发类型不匹配错误。Java 中你调用的 setText() 方法接收字符串参数,在 Kotlin 中依然可以直接使用。
正确实现方式
方式1:直接调用setText()方法(最常用,兼容性最好)
val email = findViewById<EditText>(R.id.email) // 清空输入内容 email.setText("")
如果要放在apply代码块中,写法如下:
val email = findViewById<EditText>(R.id.email).apply { setText("") }
方式2:调用Editable的clear方法
也可以直接清空已有的Editable内容,无需传入空字符串:
val email = findViewById<EditText>(R.id.email).apply { text.clear() }
内容的提问来源于stack exchange,提问作者Tatia -
相关产品推荐
相关产品推荐

