I just started learning App development with Android Studio and Kotlin, but I have a problem. In the tutorial, it is possible to access a textView from the main XML file in the main kotlin file by just writing the id of the textView. But it is not working for me. The id does not get recognised in the kotlin file, but in the video it does. I already checked if the id is correct and I have followed every step in the video.
Example:
myTextView.text = "text of myTextView"
Thanks for help in advance!
2
Answers
It requires kotlin-android-extensions but it is deprecated. So recent Android Studio may not add the required plugin to your build.gradle. You still can use it by manually adding
apply plugin: 'kotlin-android-extensions'
to build.gradle (In addition, import is required in your kt file but the IDE will automatically do it) but it is not recommended. Instead use view binding, as explained in this official docs: https://developer.android.com/topic/libraries/view-bindingIf you’re using old version of Android studio then can use
and import the following in Kotlin file
then you can directly refer to the all views that have an ID.
But if you are using latest version of Android studio then (id ‘kotlin-android-extensions) will not work as this method is deprecated. Instead what we can do is,
add following code in gradle file.
and
do the following in kotlin file ( for every XML file, a Binding class will be generated for example- in case of activity_main.XML binding class will be ActivityMainBinding):
and how to refer any ID from XML
For More detail, you can follow these links –
https://developer.android.com/topic/libraries/view-binding/migration#groovy