Search code examples
androidbottomnavigationview

How to change the icon color selected on bottom navigation bar in android studio


When I select an item in bottom navigation bar in android studio, background item selected is equal to primarycolor in values->colors.xml . and now I want to change this color which is not to same the primarycolor. how do i can to change it?

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        Fragment fragment;
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    fragment = new HomeFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.navigation_addpost:
                    fragment = new AddFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.navigation_notifications:
//                    mTextMessage.setText(R.string.title_notifications);
                    return true;
                case R.id.navigation_profile:
                    fragment = new ProfileFragment();
                    loadFragment(fragment);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        loadFragment(new HomeFragment());
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setItemTextColor(ColorStateList.valueOf(Color.RED));
    }

Solution

  • To change the selected tab icon color in BottomNavigationView you should use the Selector.

    Create bottom_navigation_selector.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:state_checked="true" android:color="@color/yourSelectedColor" />
      <item android:color="@color/defaultColor"  />
    </selector>
    

    Apply app:itemIconTint="@drawable/bottom_navigation_selector" to your BottomNavigationView in xml file.