问题
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.
回答1:
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 meansMaterialButton
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 fromButton
andAppCompatButton
. One of the main differences is thatAppCompatButton
has a4dp
inset on the left and right sides, whereasMaterialButton
does not.
This mentions only left/right inset, but the Attributes section of the readme shows that all four insets are supported:
So you could add these attributes to your <MaterialButton>
tag:
android:insetTop="0dp"
android:insetBottom="0dp"
回答2:
With the new version 1.1.0 ('com.google.android.material:material:1.1.0') if you want to override some theme attributes from a default style then you can use new materialThemeOverlay
attribute.
In your case you can do something like:
<style name="MtButtonStyle"
parent="Widget.MaterialComponents.Button">
<item name=“materialThemeOverlay”>@style/GreenButtonThemeOverlay</item>
</style>
<style name="GreenButtonThemeOverlay">
<item name="colorPrimary">@color/green</item>
</style>
来源:https://stackoverflow.com/questions/52673053/cant-use-androidbackground-with-button-from-the-new-material-components