fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(PrivateDealActivity.this, R.color.colorWhite)));
This is not working. How to change background color of floating action button
Using the material components FloatingActionButton
and a material theme by default it uses the color with the attribute colorSecondary
.
To change this color you have different options:
app:backgroundTint
attribute in xml:<com.google.android.material.floatingactionbutton.FloatingActionButton
...
app:backgroundTint=".." />
<item name="backgroundTint">
attribute <!--<item name="floatingActionButtonStyle">@style/Widget.MaterialComponents.FloatingActionButton</item> -->
<style name="MyFloatingActionButton" parent="@style/Widget.MaterialComponents.FloatingActionButton">
<item name="backgroundTint">....</item>
</style>
materialThemeOverlay
attribute to override the default color colorSecondary
only for a component: <style name="MyFloatingActionButton" parent="@style/Widget.MaterialComponents.FloatingActionButton">
<item name="materialThemeOverlay">@style/MyFabOverlay</item>
</style>
<style name="MyFabOverlay">
<item name="colorSecondary">@color/custom2</item>
</style>
You can use this code to change the background color:
FloatingActionButton button = findViewById(R.id.your_button);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && button instanceof AppCompatButton) {
((AppCompatButton) button).setSupportBackgroundTintList(ColorStateList.valueOf(*your color in integer*));
} else {
ViewCompat.setBackgroundTintList(button, ColorStateList.valueOf(*your color in integer*));
}
Please try this.
app:backgroundTint="@android:color/darker_gray"
Simply use this attribute:
android:backgroundTint="@color/yourColor"
Your code is completely correct. I also wrote in a similar way for changing background color of floating action button programatically. Just check your xml code once. My XML Code :
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
app:borderWidth="0dp"
android:id="@+id/fab"
android:layout_margin="16dp"
app:elevation="8dp"/>
Remember here, keeping borderWidth="0dp"
is important.
Now, in Java Code :
fab = view.findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(required_color));
Here you can replace required_color using Color.parseColor()
or ContextCompat.getColor()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With