带有颜色资源 : What am I doing wrong? 的 Android LinearLayout

标签 android android-layout

我关注了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/

相关文章:

android - ActionBar 方向

android - 防止图像像素化,缩进 listViews 和添加圆角

android - NavigationDrawer布局元素不可点击

android - 如何将 TableLayout 列缩小到 minWidth?

android - 来电广播接收器

android - 根据操作栏选项卡更改 Activity 内容 View

android - 如何在 Espresso 测试中调用自定义 View 的方法?

Android:检测导航栏可见性

android - 在 fragment 中动态添加 TextView

android - adjustPan 不阻止键盘覆盖 EditText