我关注了this tutorial为特定的 Android View 创建颜色状态列表。我只是希望它在单击时突出显示,以便用户知道为什么屏幕刚刚改变。
渲染 View 时,出现以下错误:
org.xmlpull.v1.XmlPullParserException:二进制 XML 文件第 3 行:标签需要“drawable”属性或定义可绘制对象的子标签
我的颜色 XML(在 res/color/viewcolor.xml 中):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#ff33ffff"/> <!-- pressed -->
<item android:color="#ff000000"/> <!-- default -->
</selector>
我的布局 XML(在 res/layout/myview.xml 中):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myview"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:background="@color/viewcolor">
<!--crap in the layout-->
</LinearLayout>
我错过了什么?
最佳答案
我记得我通过使用 state drawable 而不是 state color 解决了这个错误。由于某种原因,布局背景不适用于有状态的颜色。因此,请尝试创建一个有状态的可绘制对象(例如具有不同颜色的形状可绘制对象列表)并将其用作背景。
res/drawable/pressed.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ff33ffff" />
</shape>
res/drawable/normal.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ff000000" />
</shape>
res/drawable/background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/pressed" />
<item android:drawable="@drawable/normal" />
</selector>
然后使用 background.xml drawable 作为背景:)
关于带有颜色资源 : What am I doing wrong? 的 Android LinearLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3506319/