Cezary Łabuński
Cezary Łabuński

Reputation: 9

Android Studio - MainActivity.kt doesn't recognise any element by ID

I'm struggling with very common problem, I think.
I've created a button in xml file and tagged it with ID. Then I wanted to make onClickListener in MainActivity.kt. But when I'm typing button's ID, it's marked red and it seems like Android Studio doesn't recognise it. I've tried cleaning and rebuilding project, but the problem still exist. Invalidate Caches/Restart didn't help as well.
There are screens from Android Studio.
View from XML

View from MainActivity.kt

Thanks for your time and help!

Upvotes: 0

Views: 1365

Answers (3)

Sumit
Sumit

Reputation: 1

You need to add this in the import section

import android.widget.Button

And later in the class while referencing to the Button id you need to do this

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}
val SUB_Button = findById<Button>(R.id.SUB_Button)
<Rest code goes here>

After this your unresolved reference error will be gone.

N.B: If the code shows error try to put this lineval SUB_Button = findById<Button>(R.id.SUB_Button) in side the class MainActivity

Hope this helps :):)

Upvotes: 0

Dmitri
Dmitri

Reputation: 2972

If you want to use synthetic view bindings by Jetbrains, you need to make sure to add kotlin-android-extensions plug-in your module gradle file.

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

Stefan's answer above correcty states its considered obsolete now, but you can still use it. Or, again as in his answer, use findViewById.

Alternatively, you can use view bindings. For this, make sure to have this entry inside your Android section in your gradle file:

buildFeatures{
        viewBinding = true
    }

Refer to https://developer.android.com/topic/libraries/view-binding for how to use it.

Upvotes: 4

Stefan Zhelyazkov
Stefan Zhelyazkov

Reputation: 2981

What you are trying to do is using synthetic view bindings in Android Studio. As far as I found online, they are not recommended anymore. Use findViewById instead:

val button = findViewById<Button>(R.id.SUB_button)
button.setOnClickListener { ... }

Upvotes: 1

Related Questions