androidkotlin

Why does Kotlin Activity have a problem finding Buttons?


Attempting to update an older Android game project to use view binding. Android Studio version 4.1.3. I am thinking my problem has to do with the naming of my binding class. the xml file is called activity_correct_guess.xml and I am using what I think is the name that gets generated by the view binding: ActivityCorrectGuessBinding. Appreciate and ideas!

The build errors:

Unresolved reference: ActivityCorrectGuessBinding Unresolved reference: binding Unresolved reference: binding

In the Gradle build module I have the following:

    android {
       compileSdkVersion 30
       buildToolsVersion "30.0.0"  
    buildFeatures {
        viewBinding = true
    }

layout file: activity_correct_guess.xml

   <Button
    android:id="@+id/btnPlayAgain"
    android:layout_width="wrap_content"
   ..... />

Activity file: CorrectGuessActivity.kt

      class CorrectGuessActivity : AppCompatActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      val binding = ActivityCorrectGuessBinding.inflate(layoutInflater)
      val view = binding.root
      setContentView(view)

      playAgain()
      exitGame()
   }

fun playAgain() {
    binding.btnPlayAgain.setOnClickListener {
        val intent = Intent("com.appkotlin2021v4.MainActivity")
        startActivity(intent)
    }
}

Solution

  • Typically, you define your view binding in the root of your Activity or Fragment or in an init block:

    class CorrectGuessActivity : AppCompatActivity() {
        //get to inflating!
        private val binding = ActivityCorrectGuessBinding.inflate(layoutInflater)
        
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(binding.root)
            playAgain()
            exitGame()
        }
    
        fun playAgain() {
            binding.btnPlayAgain.setOnClickListener {
                val intent = Intent("com.appkotlin2021v4.MainActivity")
                startActivity(intent)
            }
    }
    

    The only time you need to "wait to inflate" is when you're in a non-ViewGroup-based class like RecyclerView.Adapter, etc.