Search code examples
androidxmlandroid-studiobottomnavigationviewappcompatactivity

How to change the color of a specific element BottomNavigationView using ColorStateList?


Trying to default BottomNavigationView two colors (for the two States of the menu items) add a third condition and a third color. For this in the drawable created a file "bottom_nav_colors.xml" with the selectors:

<?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/colorPrimaryDark"/>
    <item android:state_activated="true"  
        android:color = "@color/colorAccent"/>
    <item android:color = "@color/colorGray" />
</selector >

The file with layout template "activity_main.xml" pointed out:

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation_menu"
    app:itemIconTint="@drawable/bottom_nav_colors"
    app:itemTextColor="@drawable/bottom_nav_colors"/>

However, I can not figure out what method of class "BottomNavigationView" out of class "MainActivity.java" (inherited from class "MvpAppCompatActivity") to activate it for my menu item as "activated" (or any other from the list: "accelerated", "active", etc.).

Or if you can't do that, then how can?


Solution

  • Alas, "BottomNavigationView" this trick will not work. But if you use his heir out of here, it's all done easily enough:

    if (ServiceApp.getCartsGoodsNumber() > 0) {
    
        bnve.getBottomNavigationItemView(i).setIconTintList(
            ContextCompat.getColorStateList(
                bnve.getContext(),
                color.bottom_select_nav_colors));
        addBadgeAt(bnve, i, ServiceApp.getCartsGoodsNumber());
    
    } else {
    
        bnve.getBottomNavigationItemView(i).setIconTintList(null);
    
        if (mNavigation_20Badge != null) mNavigation_20Badge.hide(true);
    }
    

    Here bnve an instance of the class "BottomNavigationViewExe", and the method addBadgeAt() looks like this:

    private void addBadgeAt(BottomNavigationViewEx bnve, 
                            final int position, final int number) {
        // add badge
        mNavigation_20Badge = new QBadgeView(bnve.getContext())
                .setBadgeNumber(number).setGravityOffset(12, 2, true)
                .bindTarget(bnve.getBottomNavigationItemView(position));
    }
    

    This method enables you to add a badge icon:

    enter image description here