以编程方式创建 MaterialButton,主题错误

Creating a MaterialButton programatically, theme error

正在尝试以编程方式创建 MaterialButton:

private val button = MaterialButton(context, null, R.style.Widget_MaterialComponents_Button)

但是我在尝试渲染时遇到以下错误:

Failed to find '@attr/textAppearanceButton' in current theme.

我试图传入一个使用我的应用程序主题的上下文,它是从.

"Theme.AppCompat.Light.NoActionBar"

初始化时尝试了多种样式,结果没有变化。

运气不好,有什么想法我做错了吗?

您需要更新您的主题以继承自 MaterialComponents 主题之一,例如:

Theme.MaterialComponents.Light.NoActionBar

https://material.io/develop/android/docs/getting-started

请注意,您应该能够通过单参数构造函数进行初始化:

private val button = MaterialButton(context)

前提是您使用的 Context 是主题(ActivityApplication 如果您在 <application> 标签上设置了主题).