Android的:改变按钮上的文字和背景颜色 [英] Android : change button text and background color
问题描述
我如何可以改变文字和背景颜色,当我的按钮是pressed,使用XML?
How can I change both text and background colors when my button is pressed, with xml ?
要改变文字颜色,我可以做的:
To change text color I can do :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="mycolor"/>
<item android:color="mycolor2/>
</selector>
要更改背景,我可以做(用它在选择器/项与绘制参考):
To change the background I can do (using it in a selector/item with drawable reference) :
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FF0079FF" />
</shape>
但我怎么能做到既?比方说,我想有:
But how can I do both ? Let's say I want to have :
- 默认:黑色文本/白色背景
- pressed:白色文本/蓝色背景
我完全以忘记的背景和文字颜色是分开管理的,所以这是我做的:
I totaly forgot that the background and text color are managed separately, so this is how I did it :
<Button
android:textColor="@color/filtersbuttoncolors"
android:background="@drawable/mybackgroundcolors" />
在mybackgroundcolors.xml我管理的背景和filtersbuttoncolors.xml我管理的文本颜色。在这两个XML文件我管理的状态(pressed,选择默认值)
In mybackgroundcolors.xml I manage the background and in filtersbuttoncolors.xml I manage the text color. In both xml files I manage the status (pressed, selected, default)
推荐答案
下面是一个绘制的例子,这将是白色默认情况下,当黑色pressed:
Here is an example of a drawable that will be white by default, black when pressed:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@android:color/black" /> <!-- pressed -->
<item android:drawable="@android:color/white" /> <!-- default -->
</selector>
此外
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<shape>
<solid
android:color="#1E669B" />
<stroke
android:width="2dp"
android:color="#1B5E91" />
<corners
android:radius="6dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#1E669B"
android:endColor="#1E669B"
android:angle="270" />
<stroke
android:width="4dp"
android:color="#1B5E91" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
这篇关于Android的:改变按钮上的文字和背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!