iT邦幫忙

1

有關Android Kotlin Thread 更新UI View text的問題

之前在網絡看到有關Android Thread的文章說,在不是UI Thread裡面執行的Logic是不能直接更新UI View。不然會有ERROR,但最近在寫的時候發現,我在Thread裡面直接更新TextView的text竟然沒問題了,想請教一下有人知道原因嗎?

        Thread {
                Log.d("MainActivity!!! ", "Thread:  Name: ${Thread.currentThread().name} ${Thread.currentThread().id}")
            tv_thread_test.text = "Thread Update"
        }.start()

執行結果:
D/MainActivity!!!: Thread: Thread-4 20432
而且UI也順利更新了

*** 之後又再測試了一下,如果在 tv_thread_test.text = "Thread Update"之前加上了Thread.sleep()之後就會ThreadException了
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

這到底是為什麼阿/images/emoticon/emoticon06.gif

另外還想請教一下,為什麼在HandlerThread裡面執行的Logic出來的
Thread.currentThread().id會跟main thread一樣呢?

        runOnUiThread {
            Log.d("MainActivity!!! ", "UI Thread:  Name: ${Thread.currentThread().name} ${Thread.currentThread().id}")
        }

        val handlerThread = HandlerThread("HandlerThread")
        handlerThread.run {
            Log.d("MainActivity!!! ", "handler thread:  ${Thread.currentThread().name} ${Thread.currentThread().id}")
        }
        handlerThread.start()

執行結果:
D/MainActivity!!!: UI Thread: Name: main 2
D/MainActivity!!!: handler thread: main 2

如果都是在同一條thread, 那我要HandlerThread幹嘛呢?

謝謝解答QQ

尚未有邦友回答

立即登入回答