关于使用MaterialCardView时闪退的原因与处理方式

最简单的方法:

加一行: 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才可以,即修改为

之后再使用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,也不会闪退。

猜你喜欢

转载自blog.csdn.net/qq_42759832/article/details/108877235