Open the sub-thread directly in the UI thread to update the contents of the TextView display, run the program we will find the following error: Android.view.viewroot$calledfromwrongthreadexception:only the Original thread that created a view hierarchy can touch it views. This is the only thread that created the control to update the contents of the control.
All UI threads are going to be responsible for creating the view and maintaining it, such as updating the display of a textview, must be done in the main thread, we can not directly in the UI thread to create a child thread, to take advantage of the message mechanism: handler, the following is the simple schematic diagram of handler: Since Android provides us with a handler mechanism to solve such problems, see the following code:
Public classHandlertestactivityextendsActivity {PrivateTextView TV; Private Static Final intUPDATE = 0; PrivateHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {//TODO receives the message and goes to update the control content on the UI thread if(Msg.what = =UPDATE) { //Bundle B = msg.getdata (); //Tv.settext (b.getstring ("num"));Tv.settext (string.valueof (msg.obj)); } Super. Handlemessage (msg); } }; /**Called when the activity is first created.*/@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); TV=(TextView) Findviewbyid (r.id.tv); NewThread () {@Override Public voidrun () {//TODO Child thread sends a message to handler via handler, handler to update the value of TextView Try { for(inti = 0; I < 100; i++) {Thread.Sleep (500); Message msg=NewMessage (); Msg.what=UPDATE; //Bundle B = new bundle (); //b.putstring ("num", "Updated value:" + i); //Msg.setdata (b);Msg.obj = "Updated Value:" +i; Handler.sendmessage (msg); } } Catch(interruptedexception e) {e.printstacktrace (); }}}.start (); }}
We are using the handler mechanism to process the thread to update the UI line program control problem