如何设置自定义按钮状态背景颜色?

How to set custom button state background color?(如何设置自定义按钮状态背景颜色?)

本文介绍了如何设置自定义按钮状态背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含可绘制对象和文本的按钮.我希望按钮的背景与提供的正常背景不同(最好是纯色).这很好用,我只需使用 XML 文件中的 android:background 属性并相应地分配颜色.但是,我希望背景在被选中或聚焦(状态选择器)时变为不同的颜色.

I have a button which contains a drawable and text. I want the background of the button to be different than the normal one provided (preferably a plain color). This works fine, I simply use the android:background attribute in the XML file and assign the color accordingly. However, I want the the background to change to a different color when selected or focused (state selector).

我尝试在一个可绘制文件夹中创建一个具有定义颜色的选择器(在处理按钮文本时效果很好),如下所示:

I attempted to create a selector in a drawable folder with the defined colors (which works well when working with the text of a button), like so:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_focused="true" android:state_pressed="false" android:color="@color/green" />
        <item android:state_focused="true" android:state_pressed="true" android:color="@color/green" />
        <item android:state_focused="false" android:state_pressed="true" android:color="@color/green" />
        <item android:color="@color/white" />
    </selector> 

并将此 xml 设置为 android:background 属性,如下所示:

and set this xml as the android:background attribute, like so:

android:background="@drawable/button_state"

但这会导致强制关闭状态:

but this causes a force close stating:

 Caused by: android.content.res.Resources$NotFoundException: File res/drawable/button_state.xml from drawable resource ID #0x7f020070

但是资源在那里.不能自定义后台状态吗?如果可以,怎么做?或者我做错了什么?感谢您的帮助!

but the resource is there. Can you not customize the background state? If you can, how? or what am I doing wrong? Thanks for the help!

推荐答案

你发布的xml适合颜色状态列表,不是可绘制的状态列表.试试这个:

The xml you posted is suitable for a color state list, not a state list drawable. Try this instead:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" >
        <shape><solid android:color="@color/green"/></shape>
    </item>
    . . .
</selector>

或者,将现有文件放入 res/color 并像使用任何其他颜色一样使用它.但是,我不记得是否可以直接使用颜色状态列表作为视图的背景.

Alternatively, put your existing file into res/color and use it as you would any other color. However, I don't remember if you can use a color state list directly as a background for a view.

这篇关于如何设置自定义按钮状态背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何设置自定义按钮状态背景颜色?

基础教程推荐