首页 > 解决方案 > 尝试使用 Kotlin 在 Android Studio 中延迟后执行行

问题描述

您好,我有 textView 元素,我正在尝试通过延迟更改其文本。例如“你好” -> 等待 1 秒 -> “世界” -> 等待 1 秒 -> “你好吗?”

当我在终端中的单独 kotlin 文件中使用我的代码时,它完全按照我想要的方式工作。当我在 MainActivity.kt 中使用代码时,它会等待 1 秒并且只放置一次文本值。我认为它同时执行所有行。但是为什么终端和ui之间存在差异。

我的代码在 Main Activity 中有一个类文件和代码

class Ball (val Ball: TextView, val time: Long){

    fun textChange(){
        Handler().postDelayed({
            Ball.text = (1..90).random().toString()
        }, time)
    }
}

在 MainActivity

class MainActivity : AppCompatActivity() {
    var resultsList = mutableListOf<Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    fun playButtonPressed(view:View){
        Ball(Ball01,1000).textChange()
        Ball(Ball01,1000).textChange()
        Ball(Ball01,1000).textChange()
        Ball(Ball01,1000).textChange()
        Ball(Ball01,1000).textChange()

    }
}

标签: androidandroid-studiokotlinandroid-handler

解决方案


这样做,您要求显示 5 个字符串,但延迟相同。

在我看来,您必须使用CountDownTimer以定期间隔显示另一段文本。

这是一个示例代码

class Ball (val Ball: TextView, val messagesList: List<String>){

    private var index = 0
    fun textChange(interval: Long) {
        val time = interval * messagesList.size
        val timer = object: CountDownTimer(time, interval) {
            override fun onTick(millisUntilFinished: Long) {
                Ball.append(" " +messagesList[index++])
            }

            override fun onFinish() {
                //nothing to do
            }
        }
        timer.start()
    }
}

class MainActivity : AppCompatActivity() {
    var messageList = mutableListOf<String>("Hello", "World", "How are you ?")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    fun playButtonPressed(view:View){
        // will update the text every second during until the list is empty
        Ball(textView, messageList).textChange(1000)
    }
}

推荐阅读