Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I periodically change background image?

I want to change the background image of my app on a one second timer (changing the background between two images) . I know how to change the image on a button press, but I'm having difficulties finding a code for the timer. What should I be doing?

Thanks.

like image 464
Sean Avatar asked Jan 19 '23 06:01

Sean


1 Answers

You could use View.postDelayed(Runanble r, long delayMillis). For example, something like:

public void onCreate() {
    ...
    ImageView backgroundImageView = findViewById(R.id.background);
    backgroundImageView.postDelayed(new Runnable() {
        static int i = 0;
        public void run() {
            ImageView.this.setImageResource(
                i++ % 2 == 0 ?
                    R.drawable.background_image1 :
                    R.drawable.background_image2);
            ImageView.this.postDelayed(this, 1000);
        }
    }, 1000);
}
like image 77
Steve Prentice Avatar answered Feb 04 '23 05:02

Steve Prentice