<item>标记需要'drawable'属性

Bar*_*chs 7 android android-layout

我想尝试非常简单的风格Button.我只是希望它在没有按下时带有文本的蓝色,在点击时带有蓝色文本的白色.

我尝试用样式和选择器来做到这一点.

在我的布局中我有这个Button:

 <Button
    android:id="@+id/button1"
    style="@style/MyButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="@string/login" />
Run Code Online (Sandbox Code Playgroud)

res/values/styles我有这个styles.xml:

<style name="MyButton">
    <item name="android:background">@drawable/btn_background</item>
    <item name="android:textColor">@drawable/btn_textcolor</item>
</style>
Run Code Online (Sandbox Code Playgroud)

当然,这两个选择中res/drawable,btn_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:color="@color/white" />
   <item android:color="@color/SapphireBlue" />
</selector>
Run Code Online (Sandbox Code Playgroud)

并且btn_textcolor.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="@color/SapphireBlue" />
    <item android:color="@color/white" />
</selector>
Run Code Online (Sandbox Code Playgroud)

我运行应用程序或打开布局编辑器时出现的错误是:

<item>标记需要'drawable'属性

我理解的消息,但是我没有被拉伸,是它是一个简单的,平坦的按钮.

我怎样才能创建这么简单的按钮?

根据这篇文章更新,它应该工作.

Har*_*ana 23

试试这种方式,希望这可以帮助您解决问题.

btn_background.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>
    <item android:drawable="@drawable/white" android:state_focused="true"></item>
    <item android:drawable="@drawable/SapphireBlue" android:state_enabled="true" android:state_focused="false" android:state_pressed="false"></item>
    <item android:drawable="@drawable/white" android:state_enabled="false"></item>
</selector>
Run Code Online (Sandbox Code Playgroud)

btn_textcolor.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/SapphireBlue" android:state_pressed="true"></item>
<item android:color="@drawable/SapphireBlue" android:state_focused="true"></item>
<item android:color="@drawable/white" android:state_enabled="true" android:state_focused="false" android:state_pressed="false"></item>
<item android:color="@drawable/SapphireBlue" android:state_enabled="false"></item>
</selector>
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的,这就是它似乎工作的原因:视图的背景需要某种类型的"Drawable".通常,颜色资源是有效的drawable.但是,如果使用状态列表,则在查找背景时,解析器似乎会检查项目的可绘制属性.这就是为什么`android:textColor`可以指向具有(并且必须具有)`android:color`的选择器,并且`android:background必须指向包含`android:drawable`的选择器.因为颜色资源是有效的drawable,你可以像往常一样使用`android:drawable = @ color/...`. (4认同)