我正在尝试创建一个从 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/