本文介绍了以编程方式将样式应用于MaterialButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a custom view extending from MaterialButton and apply style in code so I don't need to do it in 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,它的确会更改颜色.

Everything works fine but backgroundTint property. For some reason background color is not changing, and it has Theme's primary color. However, if I try to apply the style to a MaterialButton in xml it does change the color.

有什么想法为什么会发生或者我如何实现?

Any idea why that can be happening or how I can achieve it?

推荐答案

我也面临着同样的问题.到目前为止,我发现的唯一解决方法是以编程方式将色调设置为:

I'm also facing the same issue. The only workaround I've found so far is to set the tint programmatically like:

button.setBackgroundTintList(ColorStateList.valueOf(Color.RED));

这篇关于以编程方式将样式应用于MaterialButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 05:19