How to change background color randomly every second programmatically in Kotlin for Android

Viewed 292

I am working on my little Android project where the requirement is to change background color randomly every second. There is any way to do this?

Please prefer the kotlin language because I'm a beginner in development.

1 Answers

It is very easy but tricky. I am using the handler Runnable method to trigger every second random function and create a new color. you can do like this :

val colorUpdater = object:Runnable {
  public override fun run() {
    val random = Random()
    val color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256))
    backgroundLayout.setBackgroundcolor(color)
    handler.postDelayed(colorUpdater, 1000)
  }
}
handler.post(colorUpdater)```
Related