Change FAB icon color based on w / compat libs state

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

<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 fine in API> 23, however in older versions of android it throws an exception.

This is where I got confused:

The android: tint property lives in FAB support and works if its just 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 is not. What am I doing wrong? Is it possible to change the color of the icon based on state for FAB in older versions of Android?

+7
android material-design android-styles floating-action-button
source share
1 answer

ColorStateList in android: hue was not supported until API 21.

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


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

 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 () in Android API <21

+8
source share

All Articles