I have been trying to change Material’s Floating Action Button color, but without success.

<android.support.design.widget.FloatingActionButton
    android:id="@+id/profile_edit_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    android:clickable="true"
    android:src="@drawable/ic_mode_edit_white_24dp" />

I have tried to add:

android:background="@color/mycolor"

or via code:

FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.profile_edit_fab);
fab.setBackgroundColor(Color.parseColor("#mycolor"));

or

fab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#mycolor")));

But none of the above worked. I have also tried the solutions in the proposed duplicate question, but none of them works; the button remained green and also became a square.

P.S. It would be also nice to know how to add ripple effect, couldn’t understand that either.

halfer's user avatar

halfer

19.9k17 gold badges102 silver badges189 bronze badges

asked Jun 21, 2015 at 21:20

Jjang's user avatar

5

As described in the documentation, by default it takes the color set in styles.xml attribute colorAccent.

The background color of this view defaults to the your theme’s colorAccent. If you wish to change this at runtime then you can do so via setBackgroundTintList(ColorStateList).

If you wish to change the color

  • in XML with attribute app:backgroundTint
<android.support.design.widget.FloatingActionButton
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_add"
    app:backgroundTint="@color/orange"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:fabSize="normal" >
  • in code with .setBackgroundTintList (answer below by ywwynm)

As @Dantalian mentioned in the comments, if you wish to change the icon color for Design Support Library up to v22 (inclusive), you can use

android:tint="@color/white"     

For Design Support Library since v23 for you can use:

app:tint="@color/white"   

Also with androidX libraries you need to set a 0dp border in your xml layout:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_add"
    app:backgroundTint="@color/orange"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:fabSize="normal" />

answered Jul 2, 2015 at 8:24

Marko's user avatar

MarkoMarko

20.4k13 gold badges49 silver badges64 bronze badges

9

Vijet Badigannavar’s answer is correct but using ColorStateList is usually complicated and he didn’t tell us how to do it. Since we often focus on changing View‘s color in normal and pressed state, I’m going to add more details:

  1. If you want to change FAB‘s color in normal state, you can just write

    mFab.setBackgroundTintList(ColorStateList.valueOf(your color in int));
    
  2. If you want to change FAB‘s color in pressed state, thanks for Design Support Library 22.2.1, you can just write

    mFab.setRippleColor(your color in int);
    

    By setting this attribute, when you long-pressed the FAB, a ripple with your color will appear at your touch point and reveal into whole surface of FAB. Please notice that it won’t change FAB‘s color in normal state. Below API 21(Lollipop), there is no ripple effect but FAB‘s color will still change when you’re pressing it.

Finally, if you want to implement more complex effect for states, then you should dig deeply into ColorStateList, here is a SO question discussing it: How do I create ColorStateList programmatically?.

UPDATE:
Thanks for @Kaitlyn’s comment. To remove stroke of FAB using backgroundTint as its color, you can set app:borderWidth="0dp" in your xml.

Community's user avatar

answered Aug 16, 2015 at 1:27

ywwynm's user avatar

ywwynmywwynm

11.6k7 gold badges37 silver badges53 bronze badges

9

As Vasil Valchev noted in a comment it is simpler than it looks, but there is a subtle difference that I wasn’t noticing in my XML.

<android.support.design.widget.FloatingActionButton
    android:id="@+id/profile_edit_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    android:clickable="true"
    android:src="@drawable/ic_mode_edit_white_24dp"
    app:backgroundTint="@android:color/white"/>

Notice it is:

app:backgroundTint="@android:color/white"

and not

android:backgroundTint="@android:color/white"

Taslim Oseni's user avatar

Taslim Oseni

6,08610 gold badges44 silver badges69 bronze badges

answered Feb 12, 2016 at 11:09

HenriqueMS's user avatar

HenriqueMSHenriqueMS

3,8642 gold badges31 silver badges39 bronze badges

5

if you try to change color of FAB by using app, there some problem.
frame of button have different color, so what you must to do:

app:backgroundTint="@android:color/transparent"

and in code set the color:

actionButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.white)));

answered Sep 16, 2015 at 14:07

ergo's user avatar

ergoergo

1,1169 silver badges6 bronze badges

2

just use,

app:backgroundTint="@color/colorPrimary"

dont use,

android:backgroundTint="@color/colorPrimary"

answered Mar 8, 2016 at 9:00

Ashana.Jackol's user avatar

1

The FAB is colored based on your colorAccent.

<style name="AppTheme" parent="Base.Theme.AppCompat.Light">
    <item name="colorAccent">@color/accent</item>
</style>

answered Jun 21, 2015 at 21:55

tachyonflux's user avatar

tachyonfluxtachyonflux

20.1k7 gold badges48 silver badges67 bronze badges

11

mFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(mContext,R.color.mColor)));

atoMerz's user avatar

atoMerz

7,54216 gold badges61 silver badges101 bronze badges

answered Jun 16, 2017 at 11:22

Reza Isfandyari's user avatar

1

New theme attribute mapping for Floating Action Button in material 1.1.0

In your app theme:

  • Set colorSecondary to set a color for background of FAB (maps to backgroundTint)
  • Set colorOnSecondary to set a color for icon/text and ripple color of FAB (maps to tint and rippleColor)

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- ...whatever else you declare in your app theme.. -->
    <!-- Set colorSecondary to change background of FAB (backgroundTint) -->
    <item name="colorSecondary">@color/colorSecondary</item>
    <!-- Customize colorSecondary to change icon/text of FAB (maps to tint and rippleColor) -->
    <item name="colorOnSecondary">@android:color/white</item>
</style>

answered May 15, 2019 at 23:33

luca992's user avatar

luca992luca992

1,54822 silver badges27 bronze badges

3

Other solutions may work. This is the 10 pound gorilla approach that has the advantage of being broadly applicable in this and similar cases:

Styles.xml:

<style name="AppTheme.FloatingAccentButtonOverlay" >
    <item name="colorAccent">@color/colorFloatingActionBarAccent</item>
</style>

your layout xml:

<android.support.design.widget.FloatingActionButton
       android:theme="AppTheme.FloatingAccentButtonOverlay"
       ...
 </android.support.design.widget.FloatingActionButton>

answered Nov 21, 2015 at 15:10

Robin Davies's user avatar

Robin DaviesRobin Davies

7,5451 gold badge36 silver badges50 bronze badges

3

With the Material Theme and the material components FloatingActionButton by default it takes the color set in styles.xml attribute colorSecondary.

  • You can use the app:backgroundTint attribute in xml:
<com.google.android.material.floatingactionbutton.FloatingActionButton
       ...
       app:backgroundTint=".."
       app:srcCompat="@drawable/ic_plus_24"/>
  • You can use fab.setBackgroundTintList();

  • You can customize your style using the <item name="backgroundTint"> attribute

  <!--<item name="floatingActionButtonStyle">@style/Widget.MaterialComponents.FloatingActionButton</item> -->
  <style name="MyFloatingActionButton" parent="@style/Widget.MaterialComponents.FloatingActionButton">
    <item name="backgroundTint">#00f</item>
    <!-- color used by the icon -->
    <item name="tint">@color/...</item>
  </style>
  • starting from version 1.1.0 of material components you can use the new materialThemeOverlay attribute to override the default colors only for some components:
  <style name="MyFloatingActionButton" parent="@style/Widget.MaterialComponents.FloatingActionButton">
    <item name="materialThemeOverlay">@style/MyFabOverlay</item>
  </style>

  <style name="MyFabOverlay">
    <item name="colorSecondary">@color/custom2</item>
    <!-- color used by the icon -->
    <item name="colorOnSecondary">@color/...</item>
  </style>

enter image description here

answered Aug 28, 2019 at 9:26

Gabriele Mariotti's user avatar

Gabriele MariottiGabriele Mariotti

325k97 gold badges896 silver badges846 bronze badges

The document suggests that it takes the @color/accent by default. But we can override it on code by using

fab.setBackgroundTintList(ColorStateList)

Also remember,

The minimum API version to use this library is 15 so you need to update it! if you dont want to do it then you need to define a custom drawable and decorate it!

answered Jun 24, 2015 at 18:05

Vijet Badigannavar's user avatar

5

Changing Floating action button background color by using below line

app:backgroundTint="@color/blue"

Changing Floating action button icon color

android:tint="@color/white"     

Agilanbu's user avatar

Agilanbu

2,7672 gold badges28 silver badges33 bronze badges

answered Oct 12, 2017 at 7:23

Kishore Reddy's user avatar

Kishore ReddyKishore Reddy

2,3941 gold badge19 silver badges15 bronze badges

Thanks to autocomplete. I got lucky after a few hit and trials:

    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:backgroundTint="@color/whicheverColorYouLike"

— or — (both are basically the same thing)

    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:backgroundTint="@color/whicheverColorYouLike"

This worked for me on API Version 17 with design library 23.1.0.

answered Nov 16, 2015 at 9:30

Gaurav Kumar Gupta's user avatar

0

I got the same problem and its all snatching my hair. Thanks for this
https://stackoverflow.com/a/35697105/5228412

What we can do..

 favourite_fab.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.favourite_selected));

it works fine for me and wish for others who’ll reach here.

Community's user avatar

answered Mar 22, 2016 at 17:44

Purvik Rana's user avatar

Purvik RanaPurvik Rana

1932 silver badges11 bronze badges

1

 <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    app:elevation="6dp"
    app:backgroundTint="@color/colorAccent"
    app:pressedTranslationZ="12dp"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/add"/>

Note that you add colors in res/values/color.xml
and include the attribute in your fab

   app:backgroundTint="@color/addedColor"

answered Jun 21, 2016 at 7:07

Gavine Joyce's user avatar

for Material design, I just changed the floating action button color like this,
Add the below two lines in your Floating action button xml.
And done,

 android:backgroundTint="@color/colorPrimaryDark"
 app:borderWidth="0dp"

answered Apr 25, 2020 at 7:18

Jwala Kumar's user avatar

Jwala KumarJwala Kumar

5257 silver badges9 bronze badges

When using Data Binding you can do something like this:

android:backgroundTint="@{item.selected ? @color/selected : @color/unselected}"

I have made a very simple example

answered Sep 13, 2018 at 8:50

Jan Málek's user avatar

Jan MálekJan Málek

5318 silver badges21 bronze badges

If you have a Floating Action Button with no drawable you can change the tint programmatically using:

fab.getBackground().mutate().setTint(ContextCompat.getColor(yourContext, R.color.anyColor));

answered Mar 6, 2020 at 12:30

Tom's user avatar

TomTom

611 silver badge2 bronze badges

2

i did it like this
android:background=”@color/colorAccent”
i just go to folder res then click on folder values and then on colors.xml in colors.xml I just change the color of colorAccent and call it in android:background and its done

answered Apr 29, 2018 at 16:46

sana sajjad's user avatar

The point we are missing is that before you set the color on the button, it’s important to work on the value you want for this color. So you can go to values > color. You will find the default ones, but you can also create colors by copping and pasting them, changing the colors and names. Then… when you go to change the color of the floating button (in activity_main), you can choose the one you have created

Exemple – code on values > colors with default colors + 3 more colors I’ve created:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="corBotaoFoto">#f52411</color>
    <color name="corPar">#8e8f93</color>
    <color name="corImpar">#494848</color>

</resources>

Now my Floating Action Button with the color I’ve created and named “corPar”:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_input_add"
        android:tint="#ffffff"
        app:backgroundTint="@color/corPar"/>

It worked for me. Good Luck!

answered Apr 15, 2016 at 17:16

Nidia F.'s user avatar

My solution, which worked for me with Data Binding

val color = ContextCompat.getColor(context, R.color.colorPrimary)
binding.fab.backgroundTintList = ColorStateList.valueOf(getColor)

answered Aug 26, 2020 at 15:25

PeterPazmandi's user avatar

in Kotlin:

val gray = getColor(requireContext(), R.color.green)
binding.fabSubmit.backgroundTintList = ColorStateList.valueOf(gray)

answered Jun 8, 2020 at 19:44

fullmoon's user avatar

fullmoonfullmoon

8,0705 gold badges43 silver badges58 bronze badges

You can use Extended, so set app:iconTint like this:

<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
        android:id="@+id/fAB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       
        app:icon="@drawable/d0"
        app:iconTint="@color/white"
         />

answered Apr 16, 2022 at 10:06

Mori's user avatar

MoriMori

2,8631 gold badge19 silver badges25 bronze badges

You can achieve this in Kotlin by the below code.

 binding.fabAddPostMenu.backgroundTintList =
    ColorStateList.valueOf(ContextCompat.getColor(this,R.color.complaint_red))

answered Mar 28 at 4:54

thevikasnayak's user avatar

add colors in color.xml file

add colors in color.xml file and then add this line of code…
floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.fab2_color)));

answered Aug 31, 2018 at 16:32

Progga Ilma's user avatar

Progga IlmaProgga Ilma

5786 silver badges8 bronze badges

You can use this code in case you want to change the color programmatically

floating.setBackgroundTintList(getResources().getColorStateList(R.color.vermelho));

OhhhThatVarun's user avatar

answered Jun 7, 2018 at 19:11

Diego Souza's user avatar

use

app:backgroundTint=”@color/orange” in


<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/id_share_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/share"
        app:backgroundTint="@color/orange"
        app:fabSize="mini"
        app:layout_anchorGravity="end|bottom|center" />



</androidx.coordinatorlayout.widget.CoordinatorLayout>

answered Sep 1, 2019 at 12:00

passionatedevops's user avatar

In styles.xml add:

<style name="FloatButtonSytle" parent="Widget.MaterialComponents.FloatingActionButton">
    <item name="colorAccent">@color/main_gradient_end</item>
</style>

and in your FloatingActionButton element add:

style="@style/FloatButtonSytle"

like this:

<com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/aparat_button"
            style="@style/FloatButtonSytle"
            android:layout_width="75dp"
            android:layout_height="75dp"
            />

answered Sep 5 at 9:03

Istis's user avatar

IstisIstis

1962 silver badges7 bronze badges

Android applications use the Floating Action Button for prompting the user to perform some important action within the android application. Floating Action Buttons in android applications are used to perform some important functionality within android applications. Many times in the android applications we want to change the color of our floating action button dynamically. In this article, we will take a look at How to change the color of the Floating action button in android. A sample video is given below to get an idea about what we are going to do in this article.

Note: This Android article covered in both Java and Kotlin languages. 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Working with the activity_main.xml file

Navigate to app > res > layout > activity_main.xml and add the code below. Comments are added in the code to get to know in detail. 

XML

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 

    android:id="@+id/idRLContainer"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">

    <TextView

        android:id="@+id/idTVHeading"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_above="@id/idFAB"

        android:layout_centerInParent="true"

        android:layout_margin="20dp"

        android:gravity="center"

        android:padding="10dp"

        android:text="Changing color of Floating Action Button in Android"

        android:textAlignment="center"

        android:textColor="@color/black"

        android:textSize="20sp"

        android:textStyle="bold" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton

        android:id="@+id/idFAB"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:layout_marginTop="20dp"

        android:src="@drawable/ic_android"

        app:backgroundTint="@color/purple_200"

        app:tint="@color/white" />

</RelativeLayout>

Step 3: Working with the MainActivity file 

Navigate to app > java > your app’s package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin

package com.gtappdevelopers.kotlingfgproject

import android.content.res.ColorStateList

import android.graphics.Color

import android.os.Bundle

import android.widget.Toast

import androidx.appcompat.app.AppCompatActivity

import com.google.android.material.floatingactionbutton.FloatingActionButton

import kotlin.random.Random.Default.nextInt

class MainActivity : AppCompatActivity() {

    lateinit var fabAction: FloatingActionButton

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        fabAction = findViewById(R.id.idFAB)

        fabAction.setOnClickListener {

            val color = Color.argb(255, nextInt(256), nextInt(256), nextInt(256))

            fabAction.backgroundTintList = ColorStateList.valueOf(

                color

            )

            Toast.makeText(this, "Color of FAB changed..", Toast.LENGTH_SHORT).show()

        }

    }

}

Java

package com.gtappdevelopers.kotlingfgproject;

import android.content.res.ColorStateList;

import android.graphics.Color;

import android.os.Bundle;

import android.view.View;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private FloatingActionButton fabAction;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        fabAction = findViewById(R.id.idFAB);

        fabAction.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Random rnd = new Random();

                int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));

                fabAction.setBackgroundTintList(ColorStateList.valueOf(color));

                Toast.makeText(MainActivity.this, "Color of FAB changed..", Toast.LENGTH_SHORT).show();

            }

        });

    }

}

Now run your application to see the output of the application. 

Output:

Last Updated :
24 Jul, 2022

Like Article

Save Article

В разработке приложений под Android часто возникает необходимость изменить цвет кнопки Floating Action Button. Однако, выполнить это не всегда бывает просто. Например,

В разработке приложений под Android часто возникает необходимость изменить цвет кнопки Floating Action Button. Однако, выполнить это не всегда бывает просто. Например, кажется логичным попробовать изменить цвет фона кнопки следующим образом:

&lt;android.support.design.widget.FloatingActionButton
    ...
    android:background="@color/mycolor"
/&gt;

Или же с помощью кода:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.my_fab);
fab.setBackgroundColor(Color.parseColor("#mycolor"));

Однако, эти подходы не приводят к желаемому результату. Кнопка либо остается зеленой, либо становится квадратной. Ниже представлено решение этой проблемы.

Изменение цвета кнопки:

Для изменения цвета кнопки Floating Action Button следует использовать атрибут app:backgroundTint, а не android:background. Таким образом, код будет выглядеть следующим образом:

&lt;android.support.design.widget.FloatingActionButton
    ...
    app:backgroundTint="@color/mycolor"
/&gt;

Для изменения цвета в коде можно использовать метод setBackgroundTintList:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.my_fab);
fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#mycolor")));

Добавление эффекта ripple:

Эффект ripple можно добавить с помощью атрибута app:rippleColor. Вот пример его использования:

&lt;android.support.design.widget.FloatingActionButton
    ...
    app:rippleColor="@color/mycolor"
/&gt;

В коде этот эффект можно добавить следующим образом:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.my_fab);
fab.setRippleColor(Color.parseColor("#mycolor"));

В заключение хочется отметить, что Android предоставляет разработчикам гибкие инструменты для настройки внешнего вида элементов пользовательского интерфейса. Главное — знать, как их правильно использовать.

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

To change the color of a Floating Action Button (FAB) in Android, you can use the setBackgroundTintList() method and pass it a color state list. A color state list is a set of colors that defines the colors of the FAB for different states such as enabled, pressed, and disabled.

Here is an example of how to change the color of a FAB in Android:

FloatingActionButton fab = findViewById(R.id.fab);

// create a color state list for the FAB
ColorStateList colorStateList = new ColorStateList(
        new int[][]{
                new int[]{-android.R.attr.state_enabled}, // disabled
                new int[]{android.R.attr.state_pressed}  // pressed
        },
        new int[]{
                Color.GRAY,  // disabled
                Color.BLUE   // pressed
        }
);

// set the background color of the FAB
fab.setBackgroundTintList(colorStateList);

In the example above, the color state list defines two colors for the FAB: gray for the disabled state and blue for the pressed state. When the FAB is enabled and not pressed, it will use the default color.

I hope this helps. Let me know if you have any questions.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *