【问题标题】:Changing a textView based on the value of a variable using coroutines in kotlin在 kotlin 中使用协程根据变量的值更改 textView
【发布时间】: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 的回答所建议的那样。

标签: android kotlin coroutine


【解决方案1】:

使用无限循环不是一个好习惯,使用 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)

【讨论】:

  • 变量声明出现了一些错误,但在将声明更改为私有 var isConnected 后起作用:MutableLiveData = MutableLiveData()。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2018-03-22
  • 2016-06-04
  • 2011-10-29
相关资源
最近更新 更多