Search code examples
androidandroid-viewbinding

Cannot resolve method 'getRoot()' when using viewBinding


I'm using viewBinding in my project which works perfectly. But I have an issue where getRoot() cannot be resolved in this line View view = binding.getRoot(). My code runs fine without any crashing, but I want the error to go away and just can't seem to fix the issue. I've tried disabling and re-enabling viewBinding, Invalidating caches and restarting and cleaned the project but this annoying error just doesn't seem to go away.

Here's my code

build.gradle

...
viewBinding {
        enabled = true
    }
...

MainActivity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        binding.bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
        ...
}

activityMain

...
<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation_view"
        style="@style/Widget.MaterialComponents.BottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="?attr/colorSurface"
        app:menu="@menu/bottom_nav_menu" />
...

Solution

  • I finally fixed it!!

    I read in the docs that binding.getRoot() gets the root view(the outermost view) in the corresponding layout. So I figured I'd give the root view an id and call that id instead.

    activity_main

    <RelativeLayout
            android:id="@+id/root"
            ...>
    </RelativeLayout>
    

    MainActivity

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
            View view = binding.root;
            setContentView(view);
            ...
    }