Change icones colors dynamically

Asked

Viewed 896 times

2

I have the following question: I have several icones in my design, some white and others black.

Is it possible to change the color of the icon without importing an icon already in the specific color? Ex: Let 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.

inserir a descrição da imagem aqui

The idea would be to do that in the icones of Actionbar. I wonder how I could do that and if it’s possible?

Examples & suggestions I found: (I couldn’t make it work)

1

Drawable mDrawable = context.getResources().getDrawable(R.drawable.yourdrawable); 
mDrawable.setColorFilter(new 
PorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));

2

ImageView lineColorCode = (ImageView)convertView.findViewById(R.id.line_color_code);
int color = Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);
  • Are you using Bottomnavigationview? It would be interesting to put in your question, because maybe you have more viable ways to solve the problem,.

  • Bottomnavigationview I mentioned as an example only. What I want to get right is in Actionbar, but I edited the question anyway. @acklay

1 answer

1


For this case, if you prefer, you can only use XML. Simply create a <selector> with the name for example, item_selector.xml, using the state_check as true and insert into your directory drawable, thus remaining: res/drawable/item_selector.xml. See below for 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 define the itemIconTint and the itemTextColor so that the text is also 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" />
  • I don’t want a Bottomnavigationview, I just quoted as an example. I would like to color a simple icone/image

  • @Tiagoib even so, you can use it the same way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.