Home:ALL Converter>Access to UI from background thread android

Access to UI from background thread android

Ask Time:2021-01-30T03:09:48         Author:Evgeniy Moiseev

Json Formatter

When I try o update the UI from background thread its updating, but I was expecting an exception like android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Why does this code work?

class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
lateinit var buttonUIThread: Button
lateinit var buttonAnotherThread: Button

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    textView = findViewById(R.id.textView)
    buttonUIThread = findViewById(R.id.buttonUIThread)
    buttonAnotherThread = findViewById(R.id.buttonAnotherThread)
}

fun onClick(view: View) {
    when (view) {
        buttonUIThread -> {
            textView.text = "Access to UI from thread ${Thread.currentThread().name}"
        }
        buttonAnotherThread -> {
            Thread {
                textView.text = "Access to UI from thread ${Thread.currentThread().name}"
            }.start()
        }
    }
}

}

result

Author:Evgeniy Moiseev,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/65960393/access-to-ui-from-background-thread-android
yy