'Button Id Not recognized in MainActivity.kt File Kotlin

I am new to Android App Development, and I was following a tutorial online to use Kotlin to create a basic application. In the tutorial, I got an issue with a button Id not being recognized. The Button has an id "goToAddProduct" enter image description here

enter image description here

In my MainActivity.kt, I call it however I still get an error. I have also tried to do

Button homebutton = findViewById(R.id.goToAddProduct)
homebutton.setonClickListener{...}

However I have not had any luck yet with that. Any advice would be greatly appreciated. And just remember that I am new to this and don't understand Kotlin that well. Thank you!



Solution 1:[1]

Apply these plugins in build.gradle(module) file.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

Solution 2:[2]

I had the same issue - my solution was to put id 'kotlin-android-extensions' into the plugins in the build gradle.

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

Solution 3:[3]

The problem is that your MainActivity's layout is activity_main which is set in setContentView although you're trying to access views from another layout (content_main.xml)

enter image description here

Solution 4:[4]

You need to use the Kotlin plugin to use the direct id in MainActivity

Solution 5:[5]

var homebutton : Button = findViewById(R.id.goToAddProduct) homebutton.setOnClickListener{...} must does work, with O letter in capital.

Solution 6:[6]

The way of using the id directly is deprecated.

Try:

val button = findViewById<Button>(R.id.goToAddProduct)

or

val button = findViewById<MaterialButton>(R.id.goToAddProduct)

Solution 7:[7]

Do not use Kotlin synthetics as it's already deprecated and suggested to migration on viewBinding. Check this refrence to migartion to viewBinding and accessing all references of XML file. https://developer.android.com/topic/libraries/view-binding/migration

Just Add this in your build.gradle

 buildFeatures {
        viewBinding = true
    }

So, you will be directly able to access goToAddProduct.SetOnClickListener {}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Antoine
Solution 3 Zain
Solution 4 Lalit rajput
Solution 5
Solution 6 Sam Chen
Solution 7 Hardik Paranjape