![]() |
VOOZH | about |
User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, that to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.
For example, a thread action is started, and the developer wants to update the front-end element with respect to the thread elements, the runOnUIThread{...} function can be used.
Below is an example of an application where a UI thread is used.
Initially, the application will show a Welcome message and as soon as the start button is clicked, it will show 2 messages, "love gfg" and "not gfg" alternatively at each second.
Step 1: Add the below code in activity_main.xml. Here, add a TextView and a button to our MainActivity layout.
Step 2: Add the below code in MainActivity. Here OnClickListener is added with the button. So it is invoked whenever the user clicks the button. In the listener, an infinite loop is created in the main thread and using the UI thread the text is changed after every second.
Note: The While loop must be declared only inside the Thread. If a Thread is declared inside a while loop, the program doesn't work and crashes.
From the basic concept of the above code, a timer app can be designed. Below is the code for the same:
Approach:
Step 1: Add the below code in MainActivity layout. Here a button, edittext, and textview are added. The button is used to start the timer, edittext is used to take the input from the user, and textview is used to display the time left.
Step 2: Add the below code in MainActivity class. Here we add the onClickListener with the button. As the button is clicked, runOnUiThread function is used to display the time left.