Home » Android » android – Extending MaterialCardView doesn't apply themes-Exceptionshub

android – Extending MaterialCardView doesn't apply themes-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

According to the material specifications https://material.io/develop/android/components/material-card-view/ colorSurface applies to the card’s Background color .

This works when we are specifying the card in our xml like this

<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 . 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.

Is this a known issue ?

How to&Answers:

In your constructor you are using defStyleAttr: Int = 0.
You should apply the R.attr.materialCardViewStyle as default value instead of 0.

In this way your custom CardView will use the style defined in you app theme by materialCardViewStyle attribute.

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>