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.
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.
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
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.
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'
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With