Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved Reference: findViewById in Kotlin

Tags:

android

kotlin

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.

like image 316
Khayyam Avatar asked May 25 '17 13:05

Khayyam


People also ask

How do I stop findViewById in Kotlin?

Kotlin Android Extensions is a great way to avoid writing findViewById in the activity or fragment. Simply, add the kotlin-android-extensions plugin to the module level build. gradle file.

What is findViewById () method used for?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

Do we need findViewById in Kotlin?

Kotlin Android Extensions To solve the issue of writing useless code, JetBrains has created the Kotlin Android Extensions which have a number of features, but exist primarily to avoid the need for findViewById code. Using them is straightforward, you simply need to import kotlinx.


2 Answers

It seems this is the easiest way to get rid of findViewById ()

Go to your Build.Gradle (Module: app)

Add the following line

apply plugin: 'kotlin-android-extensions'
  • Then it will ask you to sync
  • Then press sync

After that come to your Activity file Say it many be MainActivity.kt

There import To import single view

import kotlinx.android.synthetic.main.<layout_name>.<view_name>;

or

To import all views

import kotlinx.android.synthetic.main.<layout_name>.*;

Example : in your Layout

<Checkbox id="@+/forwardBox" . .  . />

it is in activity_main layout then import as

import kotlinx.android.synthetic.main.activity_main.forwardBox;

so either in your function or class use it directly

forwardBox.isChecked = false
like image 176
Sudarshan Avatar answered Sep 19 '22 20:09

Sudarshan


In Kotlin you do not need to use findViewById, Simply use id ForwardBox from kotlinx.android.synthetic.<your layout name>. All used elements in your code gets automatically found and assigned to same variable name as ids in layout(xml) by kotlin.

For example:

fun init(){
    ForwardBox.isChecked = false
}
like image 43
chandil03 Avatar answered Sep 20 '22 20:09

chandil03