小编MAD*_*LAD的帖子

如何从协程后台线程更新 UI 线程?

我有一个函数 displayDirectoryContents2(file: File) 它扫描所有文件并检查文件和目录。我想要的是在 UI 线程的 textview 中显示当前文件路径

lateinit var textView: TextView


GlobalScope.launch(Dispatchers.IO) {
 displayDirectoryContents2(file)
}
Run Code Online (Sandbox Code Playgroud)

函数代码

private fun displayDirectoryContents2(dir: File?){
    try {
        val files = dir?.listFiles()!!

        files.forEach {

            if (it.isDirectory) {
                displayDirectoryContents2(it)
            } else { 
                   if (it.isFile) {
                    textView.text = it.name // to Update the file name in UI thread
              }
        }


    } catch (e: IOException) {
        e.printStackTrace()
    }
}
Run Code Online (Sandbox Code Playgroud)

我是 Kotlin 协程的新手。实际上我想在后台线程中运行函数 displayDirectoryContents2(file: File) 并更新函数在 UI 线程中读取的文件的名称,就像 AsyncTask 一样。

android kotlin kotlin-coroutines

7
推荐指数
1
解决办法
5207
查看次数