[Solved] MainActivity.kt doesn’t see button’s id?


You’re writing your code outside of MainActivity‘s onCreate (or any other) method scope.

Your code is:

class MainActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    button3.setOnClickListener { }
}

But must be:

class MainActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button3.setOnClickListener { 
            // do something
        }
    }
}

You can use class-level declaration for methods, inner classes etc, but not for writing code.

And calling views directly by their ids is possible only using Kotlin Android Extensions. Check if you’re using it and move your code to the one of methods’ scope, and code will works.

solved MainActivity.kt doesn’t see button’s id?