android - 以编程方式将样式应用于 MaterialButton

标签 android android-button android-theme android-styles material-components-android

我正在尝试创建一个从 MaterialButton 扩展的自定义 View 并在代码中应用样式,因此我不需要在 xml 中执行此操作。

class CustomRedButton @JvmOverloads constructor(
    context: Context, 
    attrs: AttributeSet? = null, 
    defStyleAttr: Int = 0
) : MaterialButton(ContextThemeWrapper(context, R.style.ButtonRedStyle), attrs, defStyleAttr) 

风格是:

<style name="ButtonRedStyle" 
    parent="Widget.MaterialComponents.Button.TextButton">
    <item name="backgroundTint">@color/red</item>
    <item name="rippleColor">@color/grey</item>
    <item name="strokeWidth">1dp</item>
    <item name="strokeColor">@color/black</item>
</style>

一切正常,但 backgroundTint 属性。由于某种原因,背景颜色没有改变,它具有主题的原色。但是,如果我尝试将样式应用于 xml 中的 MaterialButton,它确实会改变颜色。

知道为什么会发生这种情况或我如何实现它吗?

最佳答案

使用

MaterialButton(ContextThemeWrapper(context, R.style.ButtonRedStyle), attrs, defStyleAttr)

您正在将 themeoverlay 应用到默认样式,您应用不同的样式。

意思是:

<style name="ButtonRedTheme" parent="...">
    <item name="colorPrimary">@color/...</item>
    <item name="colorOnPrimary">@color/...</item>
    <item name="colorSecondary">@color/...</item>
</style>

如果您想应用不同的样式,您必须:

  • attrs.xml 中定义自定义属性
    <attr name="myButtonStyle" format="reference"/>
  • 在您的应用主题中为该属性指定样式:
   <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
        <item name="myButtonStyle">@style/CustomButtonStyle</item>
   </style>
  • 定义自定义样式:
    <style name="CustomButtonStyle" parent="Widget.MaterialComponents.Button.*">
        <item name="backgroundTint">@color/...</item>
        <item name="rippleColor">@color/grey</item>
        <item name="strokeWidth">1dp</item>
        <item name="strokeColor">@color/black</item>
    </style>

最后使用:

val customButton = MaterialButton(context, null, R.attr.myButtonStyle)

关于android - 以编程方式将样式应用于 MaterialButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52401709/

相关文章:

Android - 如何从相机捕获图像或从库中添加

android - Firebase 应用内消息传递 - Android 中的 PERMISSION_DENIED(请求被阻止的问题)

php - 从 MySQL 获取数组到 android

android - Firebase ServerTimestamp 对每个国家/地区应用相同的时间戳吗?

java - 带按钮的 getTag 和 setTag

android - 在 Android Manifest 中更改主题会导致应用程序崩溃 - 简单的解决方案?

android - AppCompatEditText 的默认背景是什么?

Android复合按钮通过xml文件

android - 如何更改操作栏菜单充气图标颜色

android - 在应用程序类中更改整个应用程序的主题