【发布时间】:2020-06-13 15:45:22
【问题描述】:
我有一个布尔变量 isConnected。我想在这个变量的基础上改变一个 textView 。 例如
if (isConnected):
textView text = a
else
textView text = b
此代码应在整个程序中运行。我尝试在 Android Studio 中实现此功能,但该应用无法加载任何内容。
var isConnected = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setStatusBar()
}
private fun setStatusBar() {
CoroutineScope(Main).launch {
while(true){
checkConnection()
}
}
}
@SuppressLint("SetTextI18n")
private fun checkConnection() {
CoroutineScope(Main).launch {
if(!isConnected){
status.text = "Disconnected"
}
else{
status.text = "Connected"
}
}
}
当我更改 isConnected 的值时,我希望应用程序更改状态文本视图中的文本, 谁能告诉我为什么我的代码不起作用?
【问题讨论】:
-
主线程中的无限循环是灾难性的,它永远不会完成执行,因此不会启动其他协程。我建议添加延迟,或者观察者更保守,正如@ApacheOne 的回答所建议的那样。