I'm trying to switch my Android project to Kotlin. I have an EditText
(a subclass of TextView
) for which I want to set a hint and text programmatically. The hint works as expected. For text, though, I'm getting a type mismatch exception if I try to do it using Kotlin setter syntax:
val test = EditText(context)
test.setHint("hint") // Lint message: "Use property access syntax"
test.hint = "hint" // ok
test.setText("text") // ok (no lint message)
test.text = "text" // Type mismatch: inferred type is kotlin.String but android.text.Editable! was expected
If we look at the declaration, we'll find identical signatures inherited from TextView
:
public final void setHint(CharSequence hint)
public final void setText(CharSequence text)
I had an impression that x.y = z
was a shortcut for x.setY(z)
but apparently that impression was wrong. setText()
is treated as a normal method rather than a setter, but what's the difference between these two methods that makes the compiler behave differently? The only one I can think of is that TextView
has an mHint
property but I don't think it might be the case.
Another thing I don't quite understand is, where does android.text.Editable
come from? There is no corresponding setText(Editable)
method, nor is there a public field of this type.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…