life4
life4

Reputation: 75

How can I change background with random time?

I'm new on Stack Overflow and I want to learn answer this question please don't give me negative reputation.

How can I change background color with random time and everytime on Android Studio ? I'm using Kotlin language.

var counter:Int =0

        if (Random.nextBoolean())
            background.setBackgroundColor(Color.GREEN)
        else
            background.setBackgroundColor(Color.RED)

        btn_touch.setOnClickListener {

            counter += 1
            textCounter.text = counter.toString()

Upvotes: 1

Views: 711

Answers (3)

Blundell
Blundell

Reputation: 76496

A fun coroutines answer:

    var loop = true
    GlobalScope.launch(Dispatchers.IO) {
        while(loop) {
            delay(TimeUnit.SECONDS.toMillis(Random.nextLong(5)))
            withContext(Dispatchers.Main) {
                when (Random.nextBoolean()) {
                    true -> background.setBackgroundColor(Color.GREEN)
                    false -> background.setBackgroundColor(Color.RED)
                }
            }
        }
    }

This will change the color randomly between the two colors, with a random interval of 1-5 seconds.

You need the dependency in your build.gradle:

dependencies {
         implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
         implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'   
    }

Control the loop value to start and stop the randomisation. (perhaps in onResume & onPause.

You could make it choose random colors also using:

 background.setBackgroundColor(Random.nextInt(255))

Upvotes: 1

Mir Milad Hosseiny
Mir Milad Hosseiny

Reputation: 2857

Try the following code snippet

val maxDelay = 10000L
val handler = Handler()
var isRed = true;
val updateRunnable = object : Runnable {
    override fun run() {
        background.setBackgroundColor(if(isRed) Color.RED else Color.GREEN)
        isRed = !isRed
        handler.postDelayed(this, Random.nextLong(maxDelay))
    }
}
handler.post(updateRunnable)

Set maxDelay value as you need and don't forget to call handler.removeCallbacks(updateRunnable) when you don't need it anymore.

Upvotes: 1

Nour Eldien Mohamed
Nour Eldien Mohamed

Reputation: 961

you can add CheckBox when checked add green Background if not add red

btn_touch.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener
        { compoundButton, ischecked ->
            if (ischecked) {
            background.setBackgroundColor(Color.GREEN)
            } else{
            background.setBackgroundColor(Color.RED)

              }
        })

but if you want to add random every press give you Different color you can follow this question. Android: Set Random colour background on create

I hope it will help you .

Upvotes: 0

Related Questions