简体   繁体   English

扩展 MaterialCardView 不应用主题

[英]Extending MaterialCardView doesn't apply themes

According to the material specifications https://material.io/develop/android/components/material-card-view/ colorSurface applies to the card's Background color .根据材质规范https://material.io/develop/android/components/material-card-view/ colorSurface 适用于卡片的 Background color 。

This works when we are specifying the card in our xml like this当我们像这样在 xml 中指定卡片时,这会起作用

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

When I run this I can see color surface properly being applied to the above card.当我运行它时,我可以看到颜色表面正确地应用于上面的卡片。

This also works if I make a card programmatically如果我以编程方式制作卡片,这也有效

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

However once I extend from MaterialCardView to make my own custom view , it appears as if the theme connection to this is lost .但是,一旦我从 MaterialCardView 扩展以制作我自己的自定义视图,就好像失去了与此的主题连接。 The color surface is not applied rather the card defaults to white不应用颜色表面,而是卡片默认为白色

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>

My CustomView now doesn't have the colorSurface applied.我的 CustomView 现在没有应用 colorSurface。

Is this a known issue ?这是一个已知的问题 ?

In your constructor you are using defStyleAttr: Int = 0 .在您的构造函数中,您使用的是defStyleAttr: Int = 0
You should apply the R.attr.materialCardViewStyle as default value instead of 0 .您应该应用R.attr.materialCardViewStyle作为默认值而不是0

In this way your custom CardView will use the style defined in you app theme by materialCardViewStyle attribute.通过这种方式,您的自定义 CardView 将使用您的应用程序主题中通过materialCardViewStyle属性定义的样式。

The default value provided by the Material Components Library is:材料组件库提供的默认值为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM