Change color icons dynamically

2

I have the following question: I have several icons in my project, some white and some black.

Is it possible to change the color of the icon without having to import an icon already in the specific color? Ex: Leave it Red, Yellow, etc ...

Example where it works but not where I need it:

BottomNavigation does this, where the icons are originally black and the color set is ColorPrimaryDark.

TheideawouldbetodothisbutintheActionBaricons.IwouldliketoknowhowIcoulddothisandifitispossible?

Examples&suggestionsIfound:(Icouldnotgetittowork)

1

DrawablemDrawable=context.getResources().getDrawable(R.drawable.yourdrawable);mDrawable.setColorFilter(newPorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));

2

ImageViewlineColorCode=(ImageView)convertView.findViewById(R.id.line_color_code);intcolor=Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);
    
asked by anonymous 15.09.2017 / 14:15

1 answer

1

In this case, if you prefer, you can only use XML. It would be enough to create a <selector> with the name, for example, item_selector.xml , using state_check as true and insert in your drawable directory, thus: res/drawable/item_selector.xml . Here is an example:

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

To use, you need to set itemIconTint and itemTextColor so that the text also stays the same color when it is selected. See:

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:itemIconTint="@drawable/item_selector"
    app:itemTextColor="@drawable/item_selector"
    app:menu="@menu/bottom_nav_bar_menu" />
    
15.09.2017 / 16:28