Article Source: http://www.2cto.com/kf/201302/190591.html
Two ways to update the UI for Android--handler and Runonuithread ()
In the Android development process, it is often necessary to update the UI of the interface. The update UI is to be updated by the main thread, which is the UI thread update. If you update the page directly in a thread other than the main thread, the error often appears. Throw exception: Android.view.viewroot$calledfromwrongthreadexception:only The original thread that created a view hierarchy can tou CH its view. Only the thread that originally created this view hierarchy (view hierachy) can modify it's views (view) without saying much, post the following code method one: in Activity.oncreate (Bundle Savedinstancestate) Creates an instance of the handler class that invokes the function displayed in the update interface in the Handlemessage callback function of the handler instance. Interface:
Public classMainactivityextendsActivity {PrivateEditText Uitxt; PrivateButton updateuibtn; PrivateUihandler Uihandler; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Uitxt=(EditText) Findviewbyid (r.id.ui_txt); UPDATEUIBTN=(Button) Findviewbyid (R.ID.UPDATE_UI_BTN); Updateuibtn.setonclicklistener (NewView.onclicklistener () { Public voidOnClick (View v) {//TODO auto-generated Method StubUihandler =NewUihandler (); Uithread Thread=NewUithread (); Thread.Start (); } }); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_main, menu); return true; } Private classUihandlerextendshandler{@Override Public voidhandlemessage (Message msg) {//TODO auto-generated Method Stub Super. Handlemessage (msg); Bundle Bundle=Msg.getdata (); String Color= bundle.getstring ("Color"); Uitxt.settext (color); } } Private classUithreadextendsthread{@Override Public voidrun () {Try{Thread.Sleep (3000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Message msg=NewMessage (); Bundle Bundle=NewBundle (); Bundle.putstring ("Color", "yellow"); Msg.setdata (bundle); Mainactivity. This. Uihandler.sendmessage (msg); } } }
After update: Method two: Use Activity.runonuithread (Runnable) to create the code that updates the UI in Runnable, and then, when you need to update the UI, Pass this Runnable object to Activity.runonuithread (Runnable). This way, the runnable can be called in the UI program. If the current thread is the UI thread, then the action is performed immediately. If the current thread is not the UI thread, the action is the UI thread that publishes to the event queue
FusionField.currentActivity.runOnUiThread (new Runnable () { publicvoid Run () { "Update My UI", Toast.length_long). Show (); } });
From for notes (Wiz)
Two ways to update the UI for Android--handler and Runonuithread ()-$firecat code Trail $-Blog channel-csdn.net