Why do I write this article
Do you often see a lot of books saying: You can't manipulate the UI in a child thread, or you'll get an error. Do you also encounter the following puzzle (see the code below):
(Bundle savedinstancestate) {
. onCreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
TV = (TextView) Findviewbyid (r.id.tv);
Thread.CurrentThread (). SetName ();
Looperthread (). Start ();
}
{
() {
thread.currentthread (). SetName ();
Tv.settext ();
}
It does manipulate the UI in a child thread, but he doesn't give an error. Isn't that exactly what the book says? At that time, I also encountered this problem, so with this blog, thanks to the network of the predecessors of the selfless sharing, and now their own sorting and thinking record down.
Second, introduce
During the Android development process, it is often necessary to update the UI of the interface. The update UI is for the main thread to be updated, that is, the UI thread update. If the page is updated directly in a thread other than the main thread, the error is often displayed. Throw exception: Android.view.viewroot$calledfromwrongthreadexception:only The original thread that created a view hierarchy can tou Ch its views. How do you solve it? Below I will detail how the child thread updates the UI:
Third, child thread update UI method
1, with Handler+message
Handler is defined in the main thread, the child thread sends a message, and notifies handler that the UI update is complete.
Mhandler = Handler () {
(message msg) {
Mytext.settext (information from the network);
. Handlemessage (msg);
}
;
{
() {
loadnetwork ();
msg = Message ();
Mhandler.sendmessage (msg);
}
The schematic diagram of the handler is as follows:
2. Update with Runonuithread
This is the best use, where you want to refresh the page, you can write the following way.
Thread () {() {Runonuithread (Runnable () {() {
imageview.setimagebitmap (bitmap);
}
});
}
}. Start ();
This approach is more flexible to use, but if thread definition is elsewhere, it needs to pass the activity object (passed through the constructor).
3, View.post (Runnable R)
Method Explanation: Derive your subclass from Runnable and overload the Run () method. Then call View.post (myrunnableobj) to add your Runnable object to the UI thread to run.
(View v) {
Thread (Runnable () {() {loadnetwork ())
;
MyText. ( Runnable () {
mytext.settext (information from the network);
});
}
). Start ();
}