1

I'm trying to run code from Chapter 5 "Android Application Development All-in-One for Dummies".

The code in the book refers directly to view Id's in an onButtonClick function

fun onButtonClick(view: View){
...
 
        if (checkBox.isChecked()){
            ...
        }

but Android Studio highlights checkBox as an unresolved reference.

What I tried

I tried changing

fun onButtonClick(view: View){
...
        val checkBox = view.findViewById<CheckBox>(R.id.checkBox)
        if (checkBox.isChecked()){
            ...
        }

but that crashed at runtime with checkBox is null. I looked at How can you add a reference to another view through attributes in android? and tried changing

fun onButtonClick(view: View){
...
        val vp : ViewGroup = view.getParent()
        val checkBox = vp.findViewById<CheckBox>(R.id.checkBox)
        if (checkBox.isChecked()){
            ...
        }

but that got type mismatch: inferred type is ViewParent (which doesn't have findViewByID)

  • Does this answer your question? [Unresolved reference - activity does not recognize synthetic imports in android studio v4](https://stackoverflow.com/questions/64716903/unresolved-reference-activity-does-not-recognize-synthetic-imports-in-android) – a_local_nobody Mar 10 '21 at 10:44
  • if you're in a fragment/activity, just use findViewById – a_local_nobody Mar 10 '21 at 10:45
  • `The code in the book refers directly to view Id's in an onButtonClick function` see the link i provided above. synthetic imports are deprecated and new projects don't have the import anymore – a_local_nobody Mar 10 '21 at 10:46

1 Answers1

1

let me write a complete answer

you say:

The code in the book refers directly to view Id's in an onButtonClick function

These are synthetic imports for kotlin, but they're deprecated and new projects don't have these added by default anymore. so your alternative is either ViewBinding or findViewById

in your situation (without seeing your code)

i'm going to assume you just need findViewById and don't need a view reference, so you should be able to do:

fun onButtonClick(view: View){
...
    val checkBox = findViewById<CheckBox>(R.id.checkBox)
    if (checkBox.isChecked()){
        ...
    }

what happens in the following code:

fun onButtonClick(view: View) {

well, the view which has triggered onButtonClick is passed through, so in your case, if you're pressing a button, then the actual button is passed to you here, so if you use view.findViewById<CheckBox>(R.id.checkBox) you're trying to find your checkbox on the button itself, which doesn't work.

by just using findViewById<CheckBox>(R.id.checkBox), that's a reference to the root layout and your checkbox should then be found

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51