Android ViewBinding unable to render LinearLayout configuration

Viewed 417

The ViewBinding implementation is unable to render the layout configuration for LinearLayout used in my code, while the same layout works with the older technique of findViewById()

I have setup the gradle to use ViewBinding

android {
    ...
    buildFeatures {
        viewBinding = true
}

Below is the activity which uses a LinearLayout

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:orientation="vertical"
    tools:context=".MainActivity">

  <ImageView
        ... />

  <Button
        ... />

</LinearLayout>

The corresponding Kotlin class includes the binding instance with its root view passed to setContentView()

MainActivity.kt

private lateinit var binding: ActivityMainBinding

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

    setContentView(binding.root)
}

While the Layout editor renders a correct alignment of the app, once it is launched onto the emulator the layout configuration such as center_vertical alignment set using layout_gravity of LinearLayout is ignored.

Is something incorrect or missing the way ViewBinding is implemented?

3 Answers

in your activity_main.xml give id to your LinearLayout

There are one possibility is that your LinearLayout have not any id.

When you are doing binding.root it keeps a reference of root view which is LinearLayout in your case.

As per the official document:

If view binding is enabled for a module, a binding class is generated for each XML layout file that the module contains. Each binding class contains references to the root view and all views that have an ID.

Give id to your LinearLayout android:id="rootView, rebuild your project and try to run. I hope, it will solve your issue.

Thanks & Happy coding..!

Had the same issue, Solved with adding android:gravity="center_vertical" to LinearLayout in activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:layout_gravity="center_vertical"
    android:orientation="vertical"
    android:id="@+id/root_view"
    tools:context=".MainActivity">

</LinearLayout>
Related