Can't use android:background with button from the new material components

humazed picture humazed · Oct 5, 2018 · Viewed 12k times · Source

I'm using the new material components com.google.android.material:material with android x but I can't set a custom background to the button.

I know that I can use app:backgroundTint to change the color

but the default background has some padding that I want to get rid of, and the old way of using android:background to set my own background but this is no longer working.

I looked at the docs but can't find any mention to this change.

Answer

Ben P. picture Ben P. · Oct 5, 2018

The documentation for the MaterialButton class says:

Do not use the android:background attribute. MaterialButton manages its own background drawable, and setting a new background means MaterialButton can no longer guarantee that the new attributes it introduces will function properly. If the default background is changed, MaterialButton cannot guarantee well-defined behavior.

However, the GitHub readme says:

Note: MaterialButton is visually different from Button and AppCompatButton. One of the main differences is that AppCompatButton has a 4dp inset on the left and right sides, whereas MaterialButton does not.

This mentions only left/right inset, but the Attributes section of the readme shows that all four insets are supported:

enter image description here

So you could add these attributes to your <MaterialButton> tag:

android:insetTop="0dp"
android:insetBottom="0dp"