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

天大地大妈咪最大 提交于 2019-12-08 17:40:23

问题


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 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:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!