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.
这篇关于如何设置自定义按钮状态背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何设置自定义按钮状态背景颜色?
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01