我在android x上使用了新的材质组件com.google.android.material:material
,但无法为按钮设置自定义背景。
我知道我可以使用app:backgroundTint
来更改颜色
但是默认背景有一些我要消除的填充,以及使用android:background
设置自己的背景的旧方法,但是这种方法不再起作用。
我查看了docs,但没有提及此更改。
答案 0 :(得分:6)
The documentation for the MaterialButton
class说:
请勿使用
android:background
属性。MaterialButton
管理其自己的背景可绘制对象,设置新的背景意味着MaterialButton
不能再保证其引入的新属性将正常运行。如果更改了默认背景,MaterialButton
将无法保证行为明确。
但是,the GitHub readme说:
注意:
MaterialButton
在视觉上不同于Button
和AppCompatButton
。主要区别之一是AppCompatButton
在左侧和右侧都有4dp
插图,而MaterialButton
没有。
这仅提及左/右插图,但是自述文件的the Attributes section显示所有四个插图均受支持:
因此您可以将以下属性添加到<MaterialButton>
标记中:
android:insetTop="0dp"
android:insetBottom="0dp"
答案 1 :(得分:2)
看着https://medium.com/@velmm/material-button-in-android-e4391a243b17,我发现app:backgroundTint
(和app:backgroundTintMode
)有效。它会更改颜色,但不会更改可绘制的选择器。
Also,您可以将<Button
替换为<android.widget.Button
。
答案 2 :(得分:2)
当我在 Button 中使用 state drawable 时,我遇到了同样的问题,但它不会改变按钮的背景。找了半天,找到了2个解决办法:
第一个解决方案是在 values/themes.xml 文件中将应用程序主题从 MaterialComponents 更改为 AppCompat。那么 state drawable 会很好用。
到
<style name="Theme.MyApplication" parent="Theme.AppCompat.DayNight.DarkActionBar">
如果您仍想使用 MaterialComponents 主题,那么您可以尝试第二种解决方案。
使用 <android.widget.Button 而不是 <按钮或com.google.android.material.button.MaterialButton
<android.widget.Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/state_test"
android:text="Button" />
我在 Here 找到的第二个解决方案
答案 3 :(得分:1)
在新版本1.1.0('com.google.android.material:material:1.1.0')中,如果您想从默认样式中覆盖某些主题属性,则可以使用新的 {{1 }} 属性。
对于您而言,您可以执行以下操作:
materialThemeOverlay
答案 4 :(得分:1)
If you want to use gradient drawable file as MaterialButton background you can follow these simple steps.
set Your MaterialButton like this below
<com.google.android.material.button.MaterialButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:backgroundTint="@null"
android:background="@drawable/group_47"
app:layout_constraintEnd_toEndOf="@+id/input_password"
app:layout_constraintStart_toStartOf="@+id/input_password"
app:layout_constraintTop_toBottomOf="@+id/input_password" />
答案 5 :(得分:0)
只需使用 android:backgroundTint
<style name="MyButtonStyle" parent="Widget.MaterialComponents.Button">
<item name="android:backgroundTint">@color/pink</item>
</style>
<com.google.android.material.button.MaterialButton
android:id="@+id/followButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/channel_header_item_margin"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/titeChannelTV"
style="@style/MyButtonStyle"/>
答案 6 :(得分:0)
谷歌设计团队决定从材料库的初始发布版本中排除功能 android:background="@drawable/"
的主要原因是让开发者能够以更快的速度为应用构建一致且具有专业外观的设计.这是因为像我这样的大多数开发者在做出与应用的设计和颜色相关的决策方面都很糟糕。
此外,我在迁移到 MDC 时发现了来自 google tutorial 的这个片段。