Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting text in EditText Kotlin

I am trying to set text in a EditText but it says:

Type mismatch. 
Required: Editable 
Found: String

My code is as follow:

String name = "Paramjeet"
val nametxt = findViewById (R.id.nametxt) as EditText
nametxt.text = name

Don't say to use setText because I am using kotlin, not Java.

like image 802
Paramjeet Singh Avatar asked Oct 09 '22 12:10

Paramjeet Singh


People also ask

Can you set text in EditText?

In android, we can set the text of EditText control either while declaring it in Layout file or by using setText() method in Activity file.


2 Answers

Use setText(String), since editText.text expects an Editable, not a String.

like image 488
nhaarman Avatar answered Oct 12 '22 01:10

nhaarman


Use setText(String) as EditText.text requires an editable at firstplace not String

WHY ?

Nice explanation by Michael given under this link. Do visit this link for more detail

When generating a synthetic property for a Java getter/setter pair Kotlin first looks for a getter. The getter is enough to create a synthetic property with a type of the getter. On the other hand the property will not be created if only a setter presents.

When a setter comes into play property creation becomes more difficult. The reason is that the getter and the setter may have different type. Moreover, the getter and/or the setter may be overridden in a subclass.

like image 48
Rahul Khurana Avatar answered Oct 12 '22 02:10

Rahul Khurana