Change Background Color of a Button in an Android Application
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.
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);
}
}
Note that you muest declare myTestButton
as final
in your onClick method.
Admin
Updated on June 15, 2022Comments
-
Admin almost 2 years
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); }
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!!