膨胀类 <unknown> 时出错

Posted

技术标签:

【中文标题】膨胀类 <unknown> 时出错【英文标题】:Error inflating class <unknown> 【发布时间】:2011-06-29 08:28:50 【问题描述】:

我正在尝试在 UI 中按自己的方式工作。我正在尝试为列表条目设置 stateListDrawable。我要做的就是在按下项目时更改列表项布局的颜色,在按下列表项时我也想更改文本的颜色。

我收到以下错误堆栈:

E/androidRuntime(  360): FATAL EXCEPTION: main
E/AndroidRuntime(  360): android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
E/AndroidRuntime(  360):    at android.view.LayoutInflater.createView(LayoutInflater.java:513)
E/AndroidRuntime(  360):    at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
E/AndroidRuntime(  360):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
E/AndroidRuntime(  360):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
E/AndroidRuntime(  360):    at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
E/AndroidRuntime(  360):    at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
E/AndroidRuntime(  360):    at android.view.LayoutInflater.inflate(LayoutInflater.java:276)

膨胀的 XML 如下:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/help_list_container"
    android:layout_
    android:layout_
    android:padding="5dip"
    android:background="@drawable/default_list_selection">
    <TextView android:id="@+id/help_list_text" 
        android:layout_
        android:layout_
        android:textSize="16sp"
        android:textColor="@drawable/help_text_color">
    </TextView>
</LinearLayout>

如果我从 xml 中删除 android:textColor 属性,我可以让程序运行。有没有办法可以使用 stateListDrawable 从 xml 控制列表项的 texColor?

stateListDrawable 适用于 LinearLayout 中的android:background,但不适用于 TextView 的 textColor 属性。状态列表xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/white"
              android:state_pressed="true" />
    <item android:drawable="@color/black" />
</selector>

我们将不胜感激。

【问题讨论】:

【参考方案1】:

我错误地使用了可绘制对象来更改 TextView 的 textColor。相反,我应该使用 ColorStateList

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_pressed="true" android:color="@color/white" />
   <item android:color="@color/black"/>
 </selector>

【讨论】:

以上是关于膨胀类 <unknown> 时出错的主要内容,如果未能解决你的问题,请参考以下文章

Xamarin - 二进制 XML 文件第 1 行:膨胀类 <unknown> 时出错

二进制 XML 文件第 28 行:二进制 XML 文件第 28 行:膨胀类 <unknown> 时出错

在测试类中膨胀 ViewBinding 时出错:Binary XML file line #38: Binary XML file line #38: Error inflating class &l

加载highchart时Android错误膨胀类<未知>

使用 Android 膨胀类片段时出错

膨胀类 RecyclerView 时出错