Skip to content Skip to sidebar Skip to footer

Reference XML Elements Directly (in Kotlin)

I am looking at an old project and noticed that I am unable to recreate the following: var name = name.text.toString() where name.text = an EditText element id in my activity_mai

Solution 1:

Your old project seem to be using now deprecated Kotlin Synthetics which allowed you to access XML views simply by specifying their ids but its deprecated now and no longer added automatically by Android Studio to a new project, that is why you have to use findViewById instead, its recommended that you migrate to ViewBinding.

Apart from this there are some issues in your code.

where name.text = an EditText element id in my activity_main.

This is wrong, element id is name, name.text referes to the text property of EditText.

And when you get text from EditText

val text = findViewById<EditText>(R.id.name)

This gives you a reference to the EditText, if you want to get value of its text property as String then you will have to write text.text.toString(). text.toString() calls toString on the EditText object


Post a Comment for "Reference XML Elements Directly (in Kotlin)"