============ Problem Description ============
private int i = 0;private int x = 0; @Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (Savedinsta Ncestate); Setcontentview (r.layout.hello_world_layout); Button B = (button) Findviewbyid (R.id.button), final TextView v2 = (TextView) Findviewbyid (R.ID.T2); new Thread () {public VO ID run () {try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace () ;} V2.settext (x + + "");};}. Start ();
The beginner wrote a thread. This will make an error and solve
============ Solution 1============
SetText need to re-draw the view, display text and re-draw the view in Android, you need to call in the main thread, or put the message into the Looper queue
============ Solution 2============
The UI control's function SetText can only be called in the UI thread, otherwise it will cause an exception.
Can be handled with Asynctask.
============ Solution 3============
Sample code
public class mainactivity extends activity {private button incbutton;private textview msgtextview;private int count = 0;@ Overrideprotected void oncreate (bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main);msgtextview = (TextView) findViewById ( R.id.msgtextview);incbutton = (Button) Findviewbyid (R.id.incbutton); Incbutton.setonclicklistener (new view.onclicklistener () {@Overridepublic void onclick (view v) {asynctask<void , void, string> thread = new asynctask<void, void, string> () {@Overridepublic string doinbackground (void... params) {count++;return String.Format ("%d", count);} @Overridepublic void onpostexecute (string msg) {msgtextview.settext (msg);}; Thread.execute ();}});}
============ Solution 4============
or wrap the thread into an inner class, and the code will be more concise and elegant:
public class mainactivity extends activity {private button incbutton;private textview msgtextview;private int count = 0;@ Overrideprotected void oncreate (bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main);msgtextview = (TextView) findViewById ( R.id.msgtextview);incbutton = (Button) Findviewbyid (R.id.incbutton); Incbutton.setonclicklistener (new view.onclicklistener () {@Overridepublic void onclick (view v) {new mytask () . Execute ();}}); private class mytask extends asynctask<void, void, string> {@ Overridepublic string doinbackground (Void... params) {count++;return string.format ("% D ", count);} @Overridepublic void onpostexecute (string msg) {msgtextview.settext (msg);}}
Android Boot thread