'Can't resolve binding in bottom navigation view

I am getting error constantly in binding.bottom_navigation.setOnItemSelectedListener(item -> { I am attachig the code below please have a look and give some solution to it.

       ActivityMainBinding binding;
    
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        replaceFragment(new HomeFragment());

        binding.bottom_navigation.setOnItemSelectedListener(item -> {

                switch (item.getItemId()) {

                    case R.id.bnav_categories:
                        replaceFragment(new GalleryFragment());
                        break;
                    case R.id.bnav_latest:
//                    replaceFragment(new GalleryFragment());
                        break;
                    case R.id.bnav_home:
                        replaceFragment(new HomeFragment());
                        break;
                    case R.id.bnav_popular:
                        replaceFragment(new SlideshowFragment());
                        break;
                    case R.id.bnav_Random:
//                    replaceFragment(new GalleryFragment());
                        break;


                }

                return true;


        });

    }

The error I am getting is:-

MainActivity.java:157: error: cannot find symbol
        binding.bottom_navigation.setOnItemSelectedListener(item -> {
               ^
  symbol:   variable bottom_navigation
  location: variable binding of type ActivityMainBinding  

The activity_main.xml file is:

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
 
 
 
 app:layout_constraintBottom_toBottomOf="@+id/nav_host_fragment_content_main"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.949"
        app:menu="@menu/bottom_navigation_menu" />


Solution 1:[1]

Make sure you have set id in BottomNavigation in xml

android:id="@+id/bottom_navigation"

Try to use it as

binding.bottomNavigation..setOnItemSelectedListener(item -> {
      //add code
});

With viewbinding views' ids are automatically converted to camelcase

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Freny Christian