现在有一个需求就是读取一个文本文件然后更新UI的TextView,使用协程方法如下:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_about -> {
showAboutWindow()
}
}
return super.onOptionsItemSelected(item)
}
private fun showAboutWindow()
{
CoroutineScope(Dispatchers.IO).launch {
val lang = resources.configuration.locales.get(0).language
val thanksFilename = String.format("thanks_%s.txt", if (lang == "zh") "zh" else "en")
val stream = InputStreamReader(assets.open(thanksFilename))
val thanks = stream.readText()
stream.close()
withContext(Dispatchers.Main) {
try {
aboutWindow.contentView.findViewById<TextView>(R.id.tvThanks).text = thanks
aboutWindow.showAtLocation(binding.root, Gravity.CENTER, 0, 0)
} catch (e: Exception) {
Log.d(TAG, e.toString())
}
}
}
}
正文完