How can i change background with random time?

折月煮酒 提交于 2020-03-04 05:05:39

问题


I'm new on stackoverflow and i want to learn answer this question please dont 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()

回答1:


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))



回答2:


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.




回答3:


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 .



来源:https://stackoverflow.com/questions/60065576/how-can-i-change-background-with-random-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!