Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change icon color of FAB based on state w/ compat libs

I am trying to change the icon color of the icon within a FAB based on the button state:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/search_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:tint="@color/add_button_tint"
    android:src="@drawable/ic_add_black_24dp" />

add_button_tint.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:color="@color/white" />

    <item android:color="@color/black"/>
</selector>

This works great in API > 23, however in older versions of android, it throws an exception.

Here is where I get confused:

the android:tint property lives within the support FAB and works if its just a color, even in older versions of android. IE this works in all versions I tested:

android:tint="@color/black

But when I use the selector it does not. What am I doing wrong? Is it possible to change the icon color based on state for a FAB in older versions of android?

like image 563
lostintranslation Avatar asked Feb 03 '17 21:02

lostintranslation


People also ask

How do you change the color of your fab on Android?

To change background color of Floating Action Button in Kotlin Android, set the backgroundTint attribute (in layout file) or backgroundTintList property (in Kotlin file) of FAB with the required color.

How do you change the icon color on flutter?

Here's how you do it: Step 1: Locate the MaterialApp widget. Step 2: Inside the MaterialApp, add the theme parameter with ThemeData class assigned. Step 3: Inside the ThemeData add the iconTheme parameter and then assign the IconThemeData . Step 4:Inside the IconThemeData add the color parameter and set its color.


1 Answers

ColorStateList in android:tint was not supported prior to API 21.

See: https://code.google.com/p/android/issues/detail?id=204671


You can use AppCompat's AppCompatResources and support-v4 DrawableCompat to support pre-lollipop. First, remove android:tint="@color/add_button_tint" from your layout. Then set the ColorStateList programmatically:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.search_button);
ColorStateList csl = AppCompatResources.getColorStateList(this, R.color.add_button_tint);
Drawable drawable = DrawableCompat.wrap(fab.getDrawable());
DrawableCompat.setTintList(drawable, csl);
fab.setImageDrawable(drawable);

See How to use setImageTintList() on Android API < 21

like image 158
Jared Rummler Avatar answered Oct 11 '22 12:10

Jared Rummler