我有一个函数 displayDirectoryContents2(file: File),它扫描所有文件并检查文件和目录。我想要的是在 UI 线程的 textview 中显示当前文件路径
lateinit var textView: TextView
GlobalScope.launch(Dispatchers.IO) {
displayDirectoryContents2(file)
}
该函数的代码
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()
}
}
我对Kotlin协程还很陌生。实际上,我想在后台线程中运行displayDirectoryContents2(file: File)函数,并在UI线程中更新函数正在读取的文件名,就像AsyncTask一样。
withContext(Dispatchers.Main){}
)。 - Animesh Sahu