Search code examples
androidbottomnavigationview

How to get the ID of something from a different fragment: Android


I am building an app using fragments, and a bottomnavigationview. I have a button in one of my fragments that when it is pressed, goes to another fragment. But when the fragment changes, the bottomNavigationView selected item does not change.

So I want to be able to get the id of the navigationView from the first fragment, and then change the selectedItem on the button click.

Here is the code for the button click:

button1.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view) {
                searchTerm = "Colorful";
                HomeFragment fragment = new HomeFragment();
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.content, fragment, "");
                fragmentTransaction.commit();
                Log.e("Home item", String.valueOf(R.id.nav_home));
                Log.e("BottomNavigationView id", String.valueOf(navigationView));
                //navigationView.setSelectedItemId(R.id.nav_home);
            }
        });

The bottomNavigationView id is returning null. So I just need to be able to get its ID from this fragment, and then use the commented out line of code to switch the selected navigation item.

And in my onCreate I have navigationView = view.findViewById(R.id.navigation);


Solution

  • You can use style to change the selected item using below code in your style class,

     // bottom theme
    <style name="Theme.App" parent="Theme.MaterialComponents">
        //style the color, size and other features of bottom navigation bar
        <item name="bottomNavigationStyle">style="@style/Widget.MaterialComponents.BottomNavigationView.Colored</item>
        <item name="colorPrimary">@color/purple_700</item>
        <item name="colorOnPrimary">@color/teal_700</item>
        <item name="actionMenuTextColor">@color/white</item>
    </style>
    

    Then use this style in your BottomNavigationView in xml file

    android:theme="@style/Theme.App"
    

    I suggest you to use Material BottomNavigationView which is easy to use and have more features to design. You can get full code from here.