Search code examples
javaandroidloopsdelay

Change color with delay


I want to change the background color of a textview when I press a button. It should do this: first be white for 10ms, and then just the regular color. Is there some kind of delay function or do I need to write my own function for this using a loop or some kind? Any tip is greatly appreciated :)

At this moment I just use

button.setBackgroundColor(Color.parseColor("#ffa500"));

Solution

  • every view have post and postDelayed methods to respectively post a runnable to the UI thread or post delayed it.

        button.postDelayed(new Runnable() {
    
        @Override
        public void run() {
        // change color in here
        }
    }, 10);
    

    edit: if you're going to be calling this very often, you can do it even better with something like this:

    int currentColor;
    private Runnable changeColorRunnable = new Runnable() {
    
        @Override
        public void run() {
            switch(currentColor){
            case Color.RED: currentColor = Color.BLACK; break;
            case Color.BLACK: currentColor = Color.RED; break;
            }
            button.setBackgroundColor(currentColor);
    
        }
    };
    

    and then:

        button.postDelayed(changeColorRunnable, 10);
    

    this will avoid unnecessary object creation and garbage collection