Caused by: android.view.InflateException: Binary XML file line #2 in com.example.materialtest:layout/fruit_item: Error inflating class com.google.android.material.card.MaterialCardView
在学习《Android第一行代码》的14.5章节深色主题的内容时,该章节是以MaterialTest项目作为示例的,并且在res目录下创建了一个values-29目录,在values-29目录下又创建了一个styles.xml文件。
书上的源码是编写如下代码:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:forceDarkAllowed">true</item>
</style>
</resources>
按照该代码编写以后,重新运行项目,发现报错:
2022-11-17 23:12:15.448 24235-24235/com.example.materialtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.materialtest, PID: 24235
android.view.InflateException: Binary XML file line #2 in com.example.materialtest:layout/fruit_item: Binary XML file line #2 in com.example.materialtest:layout/fruit_item: Error inflating class com.google.android.material.card.MaterialCardView
Caused by: android.view.InflateException: Binary XML file line #2 in com.example.materialtest:layout/fruit_item: Error inflating class com.google.android.material.card.MaterialCardView
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:852)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.inflate(LayoutInflater.java:657)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at com.example.materialtest.FruitAdapter.onCreateViewHolder(FruitAdapter.kt:22)
at com.example.materialtest.FruitAdapter.onCreateViewHolder(FruitAdapter.kt:13)
at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:7078)
...
即使定位到对应的代码也没发现哪里有错,还以为是之前学习Kotlin的时候写的几个kt文件导致的,删除以后也是一样报错。
当看到书上有一句话:
除了...属性之外,其他的内容都是从之前的styles.xml文件中复制过来的
于是,立马找到res/values/styles.xml文件,打开查看之后发现,AppTheme的parent指定的是Theme.MaterialComponents.Light.NoActionBar
:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
...
</style>
回到values-29的styles.xml文件,把parent
属性改过来,重新运行程序,发现界面风格换成了深色主题
posted on 2022-11-17 23:43 Icebreaker_7 阅读(227) 评论(0) 编辑 收藏 举报