In Android, how do I smoothly fade the background from one color to another? (How to use threads)

I found another way to change the background color if you're interested--I think using animation will be easier than what you currently have :)

If you are using API Level 11 or above, you can use ObjectAnimator on the background color of your LinearLayout.

 ObjectAnimator colorFade = ObjectAnimator.ofObject(screen, "backgroundColor", new ArgbEvaluator(), Color.argb(255,255,255,255), 0xff000000);
  colorFade.setDuration(7000);
  colorFade.start();

Also, just a quick note, the 32-bit int color codes must be used. See http://developer.android.com/reference/android/graphics/Color.html for details but you can use Color.argb, Color.rgb, the hex as I used above, or look at the int color constants.

Hope this helps!


In your loop, your setting on background is so fast that the UI is not (will not) able to schedule the update of display. Yes, you better use a second thread to update the background or else you will stall the UI thread. Try following:

LinearLayout screen;
Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    screen = (LinearLayout) findViewById(R.id.screen);

    (new Thread(){
        @Override
        public void run(){
            for(int i=0; i<255; i++){
                handler.post(new Runnable(){
                    public void run(){
                        screen.setBackgroundColor(Color.argb(255, i, i, i));
                    }
                });
                // next will pause the thread for some time
                try{ sleep(10); }
                catch{ break; }
            }
        }
    }).start();
}

This is a threaded version of your code.


Better answer to this question would be to use ObjectAnimator

ObjectAnimator colorFade = ObjectAnimator.ofObject(view, "backgroundColor" /*view attribute name*/, new ArgbEvaluator(), mContext.getResources().getColor(R.color.colorMenuOverlay) /*from color*/, Color.WHITE /*to color*/);
                colorFade.setDuration(3500);
                colorFade.setStartDelay(200);
                colorFade.start();

Tags:

Android