skip to Main Content

I am new to Android Studio. I wrote a simple code in the main_activity.xml file, with ids. But when I try to reference the ids from my MainActivity.kt file. It shows an error Unresolved reference: btnDatePicker i.e an unresolved error.

I don’t know what wrong. Here’s a screenshot of my MainActivity.kt file. As you can see, when I try to call the id btnDatePicker, it returns an error.
enter image description here

And Here’s a screenshot of my activity_main.xml, as you’ll see I have circled the particular id I’m trying to reference.

enter image description here

4

Answers


  1. Just try to rebuild project,Build -> Rebuild project
    We have 2 variant and I recommend it. I recommend you use View Binding. Because Koltin synthetic(just writing id element) is deprecated.

    To enable view binding in a module, set the viewBinding build option to true in the module-level build.gradle file, as shown in the following example:

    android {
    ...
    buildFeatures {
        viewBinding = true
    }
    

    }

    Usage

    private lateinit var binding: ActivityMainBinding 
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding(layoutInflater)
    val view = binding.root
    setContentView(view)
    }
    

    then use your xml elements

    binding.btnDataPicker.setOnClickListener {
       ...
    }
    
    Login or Signup to reply.
  2. Id cannot be referenced directly

    Under normal conditions, you can bind the control using the following code:

    val button = findViewById<Button>(R.id.btnDatePicker)
    

    and if you want to use id directly, i think this article can help you
    View Binding

    Login or Signup to reply.
  3. Just add this in your gradle file in plugins id ‘kotlin-android-extensions’

    Login or Signup to reply.
  4. plugins {
    id ‘kotlin-android-extensions’
    }

    Just add this in your gradle file in plugins id ‘kotlin-android-extensions’

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search