如何随机更改背景? [英] How can I change background with random time?

查看:83
本文介绍了如何随机更改背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Stack Overflow的新手,我想学习回答这个问题,请不要给我负面声誉.

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

如何在Android Studio上每次随机更改背景颜色?我正在使用Kotlin语言.

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

推荐答案

有趣的协程答案:

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

这将在两种颜色之间随机更改颜色,随机间隔为1-5秒.

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

您需要在build.gradle中使用依赖项:

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'   
    }

控制循环值以开始和停止随机化. (也许在onResumeonPause中.

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

这篇关于如何随机更改背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆