安卓:改变按钮背景编程 [英] Android: change button background programmatically
问题描述
我有这个颜色的资源文件
I have this resource file for colors
<resources>
<color name="CLR_BLUE">#00f</color>
<color name="CLR_RED">#f00</color>
<color name="CLR_GREEN">#0f0</color>
<color name="CLR_YELLOW">#ff0</color>
<color name="CLR_BLUE_DARK">#00a</color>
<color name="CLR_RED_DARK">#a00</color>
<color name="CLR_GREEN_DARK">#0a0</color>
<color name="CLR_YELLOW_DARK">#aa0</color>
</resources>
和该方法被调用,当用户点击四个彩色的按钮
And this method that gets called when the user clicks one of four colored Buttons
private void changeBackground(Button pressedBtn)
{
int oldColor = 0;
int newColor = 0;
if(pressedBtn == greenBtn) {
oldColor = R.color.CLR_GREEN;
newColor = R.color.CLR_GREEN_DARK;
}
else if (pressedBtn == redBtn) {
oldColor = R.color.CLR_RED;
newColor = R.color.CLR_RED_DARK;
}
else if (pressedBtn == yellowBtn) {
oldColor = R.color.CLR_YELLOW;
newColor = R.color.CLR_YELLOW_DARK;
}
else if (pressedBtn == blueBtn) {
oldColor = R.color.CLR_BLUE;
newColor = R.color.CLR_BLUE_DARK;
}
else return;
pressedBtn.setBackgroundResource(newColor);
SystemClock.sleep(500);
pressedBtn.setBackgroundResource(oldColor);
}
问题是按钮的颜色时pressed不会改变。
我走到一个调试器,它实际上达到的方法正确的点,所以这不是一个问题。我认为这个问题是在 pressedBtn.setBackgroundResource(newColor)
,但我不明白为什么。
PS:无论如何,如果你有一个更好的解决方案来改变按钮颜色时pressed,经过半秒,变回原来的颜色,让我知道
PS: Anyway, if you have a better solution to change a button color when pressed and, after a half second, change back to original color, let me know.
推荐答案
您可以使用像下面这样的XML文件,为您的按钮来创建的状态。
You could use an xml file like one below, to create states for your button.
有关属性提供的信息是这里
您只需将此XML文件复制到可绘制文件夹中的项目,将其命名例如custom_button.xml,并以
The info about attributes available is here. You simply copy this xml file to your drawables folder in your project, name it for example custom_button.xml, and reference it in your layout with
的android:背景=@绘制/ custom_button
下面是xml文件...
Here is xml file...
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape android:shape="rectangle">
<solid
android:color="#00ff00" />
<stroke
android:width="5dp"
android:color="#ff0000"
android:dashWidth="3dp"
android:dashGap="2dp" />
</shape>
</item>
<item android:state_focused="true" >
<shape>
<gradient
android:endColor="#ffffff"
android:centerColor="#ffffff"
android:startColor="#ffffff"
android:angle="270" />
<stroke
android:width="3dp"
android:color="#00ff00" />
<corners
android:radius="5dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:endColor="#ffffff"
android:centerColor="#ffffff"
android:startColor="#ffffff"
android:angle="270" />
<stroke
android:width="5dp"
android:color="#00ff00" />
<corners
android:radius="5dp" />
</shape>
</item>
这篇关于安卓:改变按钮背景编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!