使用 kotlin 中的协程根据变量的值更改 textView
Changing a textView based on the value of a variable using coroutines in kotlin
我有一个布尔变量 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 的值时,我希望应用更改状态文本视图中的文本,
谁能告诉我为什么我的代码不起作用?
使用无限循环不是一个好习惯,使用 Mutable LiveData 可以轻松实现这一点。您必须创建一个 Boolean 类型的 MutableLiveData 变量 isConnected 和观察者它的值以进行更改以相应地修改文本。
变量声明:
private val isConnected:MutableLiveData<Boolean> = MutableLiveData(false)
现在在 onCreate 中观察它的变化:
isConnected.observe(this,Observer {
newValue ->
if(!newValue){
status.text = "Disconnected"
}
else{
status.text = "Connected"
}
})
现在使用以下语法设置值:
isConnected.postValue(true)
我有一个布尔变量 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 的值时,我希望应用更改状态文本视图中的文本, 谁能告诉我为什么我的代码不起作用?
使用无限循环不是一个好习惯,使用 Mutable LiveData 可以轻松实现这一点。您必须创建一个 Boolean 类型的 MutableLiveData 变量 isConnected 和观察者它的值以进行更改以相应地修改文本。
变量声明:
private val isConnected:MutableLiveData<Boolean> = MutableLiveData(false)
现在在 onCreate 中观察它的变化:
isConnected.observe(this,Observer {
newValue ->
if(!newValue){
status.text = "Disconnected"
}
else{
status.text = "Connected"
}
})
现在使用以下语法设置值:
isConnected.postValue(true)