更改Android应用程序中按钮的背景颜色 [英] Change Background Color of a Button in an Android Application
问题描述
我想在点击按钮时更改按钮的背景颜色。我的目标是颜色应该改变5秒然后再改变为另一种颜色。
I would like to change the background color of a button when I click it. My goal is that the color should be changed for 5 seconds and then change again to another color.
按钮的原始颜色是黄色。
The original color of the button is yellow.
以下是我尝试的代码的一部分:
Here is a part of the code I have tried:
public void click(View view){
myTestButton = (Button)view;
myTestButton.setBackgroundColor(Color.BLUE);
//*Wait lines;*
myTestButton.setBackgroundColor(Color.RED);
}
按钮将颜色变为红色但从不变为蓝色。我怀疑视图直到稍后才会刷新。我希望在等待行之前刷新按钮。
我也试过 myTestButton.invalidate()
但无济于事。
The button changes color to red but never to blue. I suspect that the view does not refresh until later. I want the button to be refreshed before the wait lines.
I've also tried myTestButton.invalidate()
but to no avail.
提前致谢对于这个有一些很棒的提示!!
Thanks in advance for some great tips on this!!
推荐答案
你在等待线中使用了什么?我想那里有一个问题,因为你可能不会导致你的UI线程在那里睡觉,并且这个方法(onClick)由你的UI线程调用。
What are you using in your "wait lines"? I guess there is a problem there, as you may not cause your UI thread to sleep there, and this method (onClick) IS called by your UI thread.
我建议你使用方法 View.postDelayed(Runnable action,long delayMills
来做到这一点。
示例:
I suggest you to use the method View.postDelayed(Runnable action, long delayMills
to do that.
Example:
myTestButton.postDelayed(new Runnable() {
public void run() {
myTestButton.setBackgroundColor(Color.RED);
}
}
注意你muest声明你的onClick方法中的myTestButton
为 final
。
Note that you muest declare myTestButton
as final
in your onClick method.
这篇关于更改Android应用程序中按钮的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!