Search code examples
androidkotlinandroid-viewbinding

Android ViewBinding for Activity requires ViewGroup


For my Android app I was trying to implement the ViewBinding Google suggests these days:

https://developer.android.com/topic/libraries/view-binding

However, there (and in all tutorials) I see this approach for the binding:

binding = ResultProfileBinding.inflate(layoutInflater)

But that doesn't work when I apply this to my Activity like this:

binding = ActivityMainBinding.inflate(layoutInflater)

enter image description here

It requires another parameter of the parent:ViewGroup which I don't have in my activity. I also can't set it to null like this:

binding = ActivityMainBinding.inflate(layoutInflater, null)

Since this is a NonNull parameter.

I also tried something someone suggested like this

private lateinit var binding2: ViewDataBinding
...
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

but this also failed with the error:

NoClassDefFoundError: Failed resolution of: Landroidx/databinding/DataBinderMapperImpl;

So what am I missing? How can I get the ViewBinding of my Activity?

---- EDIT ----

So to be clear.

  1. I added android.useAndroidX=true to the gradle.properties

  2. The build.gradle file already contains

    android { compileSdk 31

     buildFeatures {
         viewBinding true
     }
    
  3. The code of the Activity looks like this:

import ...databinding.ActivityMainBinding

class MainActivity: AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   binding = ActivityMainBinding.inflate(layoutInflater)
}

}


Solution

  • Okay, turns out the issue came from my layout.

    The layout file started with a <merge tag. I assume the IDE interpreted it as a child layout for me. This didn't seem to give errors for the normal compiling but obviously the view binding was too smart to me.

    In any case, when changing it to a normal container like

    <androidx.constraintlayout.widget.ConstraintLayout
    

    it works fine. Thanks!