最簡單的方法:
加一行: android:theme="@style/Theme.MaterialComponents" ,這樣就不會閃退了。如下:
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="123dp"
android:theme="@style/Theme.MaterialComponents"/>
升級到material:1.1.0,可能會報 Error inflating class com.google.android.material.card.MaterialCardView 或 Error inflating class com.google.android.material.button.MaterialButton等錯誤,
這是因為material:1.1.0以后,部分Material控件需要MaterialComponents包下的theme才支持,而新建項目默認使用的還是Theme.AppCompat包,我們手動改成Theme.MaterialComponents即可。
例如新建項目,默認使用的theme為:Theme.AppCompat.Light.DarkActionBar,如果需要使用Material控件,則需要改成MaterialComponents包下的Light.DarkActionBar,即:Theme.MaterialComponents.Light.DarkActionBar
默認項目里,AndroidManifest里application節點的寫法,注意,重點看android:theme="@style/AppTheme"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
點進AppTheme,可以看到繼承的父theme為Theme.AppCompat目錄下的theme
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
注意,此時Theme.AppCompat下的主題是不支持MaterialCardView,MaterialButton 等控件的,需要改為Theme.MaterialComponents下的theme才可以,即修改為
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
之后再使用MaterialCardView,MaterialButton 等控件就不會報錯了。
有時候,我們並不希望項目使用MaterialComponents下的樣式,因為MaterialComponents樣式的彈窗、Snackbar等會和AppCompat樣式有很大不同,隨意修改可能達不到我們預期的效果,如果有使用AppCompat樣式的需要,我們也可以只修改目標控件下的theme值,以MaterialCardView為例,你可以把MaterialCardView的theme值改成MaterialComponents,即:
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="123dp"
android:theme="@style/Theme.MaterialComponents.NoActionBar"/>
這樣,即使使用AppCompat,也不會閃退。
原文鏈接:https://blog.csdn.net/jingzz1/article/details/104490173/