Explain Codes LogoExplain Codes Logo

Android changing Floating Action Button color

android
material-design
xml-customization
android-development
Nikita BarsukovbyNikita Barsukov·Nov 2, 2024
TLDR

Ambush your Floating Action Button's appearance! Use the trusty setBackgroundTintList method:

// Because color is the new black fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.newColor)));

Just replace R.color.newColor with whatever color you fancy in colors.xml.

Let's get practical: XML customization

Material Design says no square FABs! So, avoid android:background as it will transfigure your FAB into a sad square. Instead, pimp your FAB by:

<!-- Look ma, no squares! --> app:backgroundTint="@color/yourColor"

For those who like to live on the edge, or rather without edges, set app:borderWidth to 0dp:

<!-- Borders are so 2020 --> app:borderWidth="0dp"

Be that cool dev who keeps the ripple effect alive:

<!-- Because ripples are cooler than waves --> android:foreground="?attr/selectableItemBackgroundBorderless"

But remember, compatibility is your best friend.

Does your FAB feel flat? Give it a lift with a subtle shadow:

<!-- Keep your FAB high... in elevation --> app:elevation="6dp"

Playing with Code: Change in action

Icons need to be fashion-forward too. Dress them up in vibrant colors. Remember to consult the Design Library Fashion Manual for the rules:

<!-- Dressed to impress --> android:tint="@color/yourIconColor"

or

<!-- Cause being trendy matters --> app:tint="@color/yourIconColor"

Feeling adventurous? Get dynamic with ColorStateList.

<!-- FAB's many (color) faces --> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/pressedColor" android:state_pressed="true" /> <item android:color="@color/focusedColor" android:state_focused="true" /> <item android:color="@color/defaultColor" /> </selector>

Got pre-Lollipop devices? They'll swap ripple animations for a colorful shapeshift when pressed.

Dealing with “the other stuff”

Transparencies

For that transparent look, use:

<!-- Let's see right through you --> app:backgroundTint="@color/yourTransparentColor"

Ripples

Post 22.2.1 versions of the Material Design Library allow color control over the ripple effect.

// Ripple in [insert your color here] fab.setRippleColor(intColor);

Just remember to convert your color to the expected integer format.