【问题标题】:How to update Android Textview in an on going loop?如何在持续循环中更新 Android Textview?
【发布时间】:2019-05-28 00:46:29
【问题描述】:

我正在使用 Kotlin。我有一个将继续进行的循环。但由于某种原因,我无法更新文本视图。这是我的简化示例。

var i = 0
while (!Thread.currentThread().isInterrupted) {
    setString(i.toString())
    i++
    Log.i("Loging value of i === ", i.toString())
}


private fun setString (string : String) {
    tempText.text = string
}

【问题讨论】:

  • 日志是否显示值?
  • @ismailalaoui,日志显示的值正确。

标签: java android kotlin


【解决方案1】:

发生的情况是因为您在主/UI Thread 以外的不同 Thread 内调用 UI 更新,您的代码无法访问 UI Thread 上的 Views。

runOnUiThread 中调用更新UI 内容的代码,例如https://stackoverflow.com/a/11140429/10464730(只需复制runOnUiThread 部分)。

或者在TextView 上执行.post,就像这样https://stackoverflow.com/a/9884344/10464730。大多数时候我首先使用runOnUiThread。如果不起作用,那是我使用.post 的时候。

抱歉,我发布的代码是 Java,但我认为您可以在 Kotlin 上查找它的等效代码。

【讨论】:

  • 我想通了。虽然设置文本必须在 UIThread 上完成,所以有一个循环会阻塞 UIThread。我使用了 Handler 和 Runnable 而不是循环,现在它可以工作了。谢谢。
  • AFAIK,loop 不会阻止 UI Thread。我认为.post 是您在loops 中所需要的。好吧,HandlerRunnable 也可以。很高兴能帮上忙。
【解决方案2】:

视图只能在 UI 线程中更新。尝试这样的事情:

while (!Thread.currentThread().isInterrupted) {

 runOnUiThread(
            object : Runnable {
                override fun run() {
                    //do your view update work here
                      setString(i.toString())
                }
            }
    )
    i++
}

【讨论】:

    【解决方案3】:

    我也喜欢这种更新文本视图的协程方法,请将其放在你的 onCreate 中,还包括你的协程 gradle 实现:

        GlobalScope.launch(Dispatchers.Main) {
            var i = 0
            while (i < 100) {
                textViewId.setText("#$i")
                i++
                delay(300)
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      相关资源
      最近更新 更多