lostintranslation
lostintranslation

Reputation: 24583

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?

Upvotes: 8

Views: 1168

Answers (1)

Jared Rummler
Jared Rummler

Reputation: 38141

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

Upvotes: 8

Related Questions