【问题标题】:Extending MaterialCardView doesn't apply themes扩展 MaterialCardView 不应用主题
【发布时间】:2020-02-19 08:03:57
【问题描述】:

根据材质规范https://material.io/develop/android/components/material-card-view/colorSurface应用于卡片的背景色。

当我们像这样在 xml 中指定卡片时,这有效

<com.google.android.material.card.MaterialCardView
    android:layout_width="100dp"
    android:layout_height="100dp"></com.google.android.material.card.MaterialCardView>

当我运行它时,我可以看到颜色表面正确地应用于上述卡片。

如果我以编程方式制作卡片,这也有效

addView(MaterialCardView(this).apply {
        layoutParams = ViewGroup.LayoutParams(300,300)
    })

但是,一旦我从 MaterialCardView 扩展以制作我自己的自定义视图,似乎与此的主题连接就丢失了。不应用颜色表面而是卡片默认为白色

class CustomView @JvmOverloads constructor(
    context: Context?,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) : MaterialCardView(context, attributeSet, defStyleAttr){

}


<com.seed.formviewactivity.CustomView
        android:layout_width="100dp"
        android:layout_height="100dp"></com.seed.formviewactivity.CustomView>

我的 CustomView 现在没有应用 colorSurface。

这是一个已知问题吗?

【问题讨论】:

  • 尝试使用R.attr.materialCardViewStyle 作为默认值defStyleAttr 而不是0。
  • 解决了。将其发布为答案

标签: android material-design android-cardview material-components-android material-components


【解决方案1】:

在您的构造函数中,您使用的是defStyleAttr: Int = 0
您应该应用 R.attr.materialCardViewStyle 作为默认值,而不是 0

这样,您的自定义 CardView 将使用materialCardViewStyle 属性在您的应用主题中定义的样式。

材质组件库提供的默认值为:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
  <!-- ... -->
  <item name="materialCardViewStyle">@style/Widget.MaterialComponents.CardView</item>
</style>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 2022-11-26
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2018-04-10
    相关资源
    最近更新 更多