First, configure the <textview android:id= "@+id/textviewid" android:layout_width= "Match_parent" in the XML file Android:layout_heig ht= "Wrap_content" android:text= "Data"/> <button android:id= "@+id/butid" android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Send Message" android:layout_below= "@id/tex Tviewid "/>
The next focus is on the code snippet in mainactivity
Public class mainactivity extends activity {private button but;private TextView textview;private Handler handler; @Override protected void oncreate (bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); but= (Button) Findviewbyid (R.id.butid); textview= (TextView) findViewById ( R.ID.TEXTVIEWID); but.setonclicklistener (New ButList ()); handler =new myhandler (); } class butlist implements onclicklistener{@Overridepublic voiD onclick (VIEW&NBSP;V) {networkthread net=new networkthread (); Net.start ();} } class myhandler extends Handler{ @Override public void handlemessage ( message msg) { //toast.maketext (Getapplicationcontext (), Thread.CurrentThread (). GetName (), toast.length_long). Show (); string s= (String ) Msg.obj; textview.settext (s); } }class networkthread extends thread{@Overridepublic void run () {//analog access to the network, so when the thread is running, First sleep 2 seconds//toast.maketext (Getapplicationcontext (), thread.currentthread (). GetName (), toast.length_long ). Show ();//Gets the name of the current thread Try {thread.sleep (2000);} catch (interruptedexception e) {e.printstacktrace ();} The simulated data string s= "data obtained from the network";//texTview.settext (s); This is wrong because the Android system only operates in main thread Uimessage msg=handler.obtainmessage () ; Msg.obj=s;handler.sendmessage (msg);}}
This is just a demo of the handler demo, only for your own learning to use. Thank you.
This article is from the "Java White Battlefield" blog, be sure to keep this source http://8023java.blog.51cto.com/10117207/1662986
Handler01 in Android