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 the 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 the child thread, to take advantage of the message mechanism: handler
Public class handlertestactivity extends activity { private textview tv; private static final int update = 0; private handler handler = new handler () { @Override Public void handlemessage (message msg) { // TODO receive messages and go to update the control content on the UI thread if (msg.what == update) { // bundle b = msg.getdata (); // Tv.settext (b.getstring ("num")); &nbSp; tv.settext ( String.valueof (msg.obj)); } super.handlemessage (msg); } }; /** called when the activity is first created. */ @Override public void oncreate (bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (R.layout.main); tv = (TextView) Findviewbyid (r.id.tv); new thread () { @Override Public void run () { // TODO sub-thread sends a message to handler via handler, handler to update TextView value try { for (int i = 0; i < 100; i++) { thread.sleep (+); message msg = new message (); msg.what = update; // Bundle b = new Bundle (); // b.putstring ("num", "Updated Value:" + i); // msg.setdata (b); msg.obj = "Updated Value:" + i; &nBsp; handler.sendmessage (msg); } } catch (interruptedexception e) { e.printstacktrace (); } } }.start (); } }
We use the handler mechanism to deal with the sub-thread to update the UI line program control problem, Andrid in the development of this mechanism is often used.
The mechanism of concise handler