我有一个函数 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 一样。