java 更改 Android 应用程序中按钮的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7957494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change Background Color of a Button in an Android Application
提问by user1022419
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.
我想在单击按钮时更改按钮的背景颜色。我的目标是颜色应该改变 5 秒,然后再改变成另一种颜色。
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);
}
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.
该按钮将颜色更改为红色,但永远不会更改为蓝色。我怀疑视图直到稍后才会刷新。我希望在等待线之前刷新按钮。我也尝试过,myTestButton.invalidate()
但无济于事。
Thanks in advance for some great tips on this!!
在此先感谢您提供的一些重要提示!!
回答by Jong
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.
你在“等待线”中使用什么?我想那里有问题,因为您可能不会导致您的 UI 线程在那里休眠,并且您的 UI 线程会调用此方法 (onClick)。
I suggest you to use the method View.postDelayed(Runnable action, long delayMills
to do that.
Example:
我建议您使用该方法View.postDelayed(Runnable action, long delayMills
来做到这一点。例子:
myTestButton.postDelayed(new Runnable() {
public void run() {
myTestButton.setBackgroundColor(Color.RED);
}
}
Note that you muest declare myTestButton
as final
in your onClick method.
请注意,您必须在 onClick 方法中声明myTestButton
为final
。