0

I made a very basic dice roll app (in Kotlin) using Android Studio with an imageView and a button. The imageView's id is "imageView" and the button's id is "button". But in the MainActivity.kt file the id names are red in colour and when I hover over them it says "unresolved reference: imageView (or button)" Why is this happening and how do I solve this?

The id names are same on both the activity_main.xml and MainActivity.kt file:

[Screenshot of code sample][1]*

RedBassett
  • 3,469
  • 3
  • 32
  • 56
srishti
  • 17
  • 8

3 Answers3

2

Your activity needs to know what those names refer to, the platform doesn't automatically link views inflated from an XML layout file. Historically this is done in Android by calling the findViewById() method like this:

lateinit var myTextView

override fun onCreate(savedInstanceBundle: Bundle?) {
    super.onCreate(savedInstanceBundle)
    // The layout file is "inflated" automatically here
    setContentView(R.layout.layout_name)

    // Then we can assign a reference to views by ID:
    myTextView = findViewById<TextView>(R.id.text_view_name)
}

Since then, shortcuts have come around: Butterknife, Kotlin Synthetics, or the current accepted standard, Jetpack View Binding. if you just need to grab a few views quick call findViewByid() but as you work with Android it's worth taking the time to enable View Binding to cut down on this boilerplate code.

RedBassett
  • 3,469
  • 3
  • 32
  • 56
0

just restart by using invalidate caches/Restart as you seeing this image and after this clean and then rebuild your project

Android Studio Image

Nitin Prakash
  • 927
  • 9
  • 16
-1

You have to use kotlin extension. In your app gradle.build add apply plugin: 'kotlin-android-extensions' In your class add import for import kotlinx.android.synthetic.main.<layout>.* where is the filename of your layout.

Rajshekhar
  • 571
  • 5
  • 9