Unresolved reference: findViewById in Kotlin

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

I'm still new to Kotlin, having learned only the basic work of kotlin, I cannot access any Android widget or change its state in Android Studio, whether it be TextView or CheckBox or RadioBox.
Identical unresolved reference errors for findViewById in all cases ...
I don’t know what I am doing wrong, even java conversion produces the same errors.

+5
source share
4 answers

In Kotlin you don't need to use findViewById , just use the ForwardBox id from kotlinx.android.synthetic.<your layout name> . All used elements in your code are automatically detected and assigned to one variable name as identifiers in the kotlin layout (xml).

For instance:

 fun init(){ ForwardBox.isChecked = false } 
+4
source

This seems to be the easiest way to get rid of findViewById ()

Go to your Build.Gradle (module: application)

Add the following line

 apply plugin: 'kotlin-android-extensions' 
  • Then he will ask you to synchronize
  • Then click

After that, enter your activity file. Say it's a lot of MainActivity.kt

There import 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 layout

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

is in activity_main layout then import as

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

therefore, either in your function or in the class use it directly

 forwardBox.isChecked = false 
+4
source
 fun Tryouts() { val checkBox = findViewById(R.id.ForwardBox) as CheckBox checkBox.isChecked = false } 

In any case, consider defining your lowercase identifiers separated by underscores, for example:

 val checkBox = findViewById(R.id.forward_box) as CheckBox 
+3
source

Your code is incorrect. Please change this to.

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

In Kotlin, just declare a variable. For example: var abc

abc can be initialized with any type of object.

If we need to take a view from the layout, we must write:

 findViewById(R.id.ForwardBox) 

Then create this view.

 findViewById(R.id.ForwardBox) as CheckBox 

Then save in a variable.

 var CheckBox1 = findViewById(R.id.ForwardBox) as CheckBox 
0
source

Source: https://habr.com/ru/post/1268233/


All Articles