Search code examples
androidkotlintextview

Android kotlin textView name not detected in activity file?


I have created a textView in the android XML file and in kotlin while creating an activity, See the code below:

textViewName.setText("Hello")

Here the textViewName is showing error. But in Kotlin is it necessary to give the findViewById reference to the text view to work?


Solution

  • The trick is to use Kotlin's extension (deprecated and discouraged but can still be used).

    plugins {
        id 'com.android.application'
        id 'kotlin-android'
    
        //add this to your app gradle
        id 'kotlin-android-extensions'
    }
    

    You can now reference the textView directly on the Kotlin code without findViewById(). The other option is to go with Data and View Binding