android室库和执行程序线程异步问题

fun setRecentToTextView() {
        executor.execute(Runnable {
            var tmp = getRecentFromDB()
            if(tmp.size <1){
                frameLayout1.visibility = FrameLayout.VISIBLE
                frameLayout2.visibility = FrameLayout.INVISIBLE
            }
            else {
                frameLayout1.visibility = FrameLayout.INVISIBLE
                frameLayout2.visibility = FrameLayout.VISIBLE
                content_textView.setText(tmp[0].content)
                currentRecentIndex = tmp[0].index
            }

        })

    }

首先,getRecentFromDB()函数具有按房间库进行数据库访问的功能。因此,应该在不是main的线程中调用它。 其次,setRecentToTextView()函数用于更改每个frameLayout的可见性并设置片段的textview。 但这是由于执行者线程对视图的访问错误而导致的错误。

有什么方法可以避免此问题?

iCMS 回答:android室库和执行程序线程异步问题

有很多选择:

  1. runOnUiThread方法(如下所示)
  2. 使用Handler绑定到主循环程序。它与runOnUIThread几乎相同。
  3. LiveData-您应该将getRecentFromDB()的值包装到LiveData并在活动时观察它。
  4. Kotlin协程-您应该在getRecentFromDB中使用修饰符“ suspend”并启动协程以从中获取结果。
  5. RxJava,流程-与LiveData类似。

例如,使用 runOnUiThread 切换到UI线程的示例:

fun setRecentToTextView() {
    executor.execute(Runnable {
        var tmp = getRecentFromDB()
        // THE START OF UI BLOCK  
          runOnUiThread(Runnable { // will send it to UI MessageQueue
            if(tmp.size <1){
                frameLayout1.visibility = FrameLayout.VISIBLE
                frameLayout2.visibility = FrameLayout.INVISIBLE
            }
            else {
                frameLayout1.visibility = FrameLayout.INVISIBLE
                frameLayout2.visibility = FrameLayout.VISIBLE
                content_textView.setText(tmp[0].content)
                currentRecentIndex = tmp[0].index
            }}
        )
      // THE END OF UI BLOCK
    })

}
本文链接:https://www.f2er.com/2292210.html

大家都在问