Unresolved Reference: findViewById in Kotlin

Viewed 33336
fun Tryouts() {
var CheckBox1 : CheckBox = findViewById(R.id.ForwardBox) as CheckBox
CheckBox1.setChecked(false)
}

I'm still a beginner in Kotlin having learnt only the basic working of kotlin, I am unable refer to any android widget or change it's state in Android Studio whether it's TextView or CheckBox or RadioBox.
Same Unresolved Reference errors for findViewById in all cases...
I don't know what is it that I am doing wrong, even java conversion outputs the same errors.

8 Answers

I have faced exactly the same issue, the problem is they have upgraded everything to view binding , Try to use it as a private function inside your main class class MainActivity : AppCompatActivity() - there it worked for me.

I had that same problem, the cause was that I accidentally declared the function outside the class, where the findViewById method from AppCompatActivity is not available.

Moved it back into the scope of the class and the referenced resolved.

am an android newbie for me the below change resolved the issue.

var CheckBox1 = findViewById<CheckBox>(R.id.ForwardBox)

In the new version of kotlin and/or android studio, I just did:

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

(at the top of the build.gradle [Module] file)

Then I returned to my activity code and wrote my button name (btn_search) and android studio got the reference done

import kotlinx.android.synthetic.main.activity_main.*
Related