Handler series (7) -- Activity. runOnUiThread ()
MainActivity is as follows:
Package cc. testui3; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; import android. app. activity;/*** Demo Description: * how to change the UI in a child thread ** call Activity. runOnUiThread (Runnable runnable) method. ** the source code of this method is as follows: ** Runs the specified action on the UI thread. if the current thread is the UI * thread, then the action is Executed immediately. if the current thread is * not the UI thread, the action is posted to the event queue of the UI thread. ** @ param action the action to run on the UI thread * public final void runOnUiThread (Runnable action) {* if (Thread. currentThread ()! = MUiThread) {* mHandler. post (action); *} else {* action. run (); *} *** the comments in the source code are too detailed and considerate. just like them! * Execute the Runnable In the UI thread. * If the current thread is a UI thread, the Runnable will be executed immediately. * If the current thread is not a UI thread, call the post () method of the UI thread handler to put it into the message queue of the UI thread. * Note: do not perform time-consuming operations in runOnUiThread (Runnable runnable) ** reference: * http://blog.csdn.net/guolin_blog/article/details/9991569 * Thank you very much */public class MainActivity extends Activity {private TextView mTextView; private Activity mActivity; private Button mButton; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); init ();} private void init () {mActivity = this; mTextView = (TextView) findViewById (R. id. textView); mButton = (Button) findViewById (R. id. button); mButton. setOnClickListener (new OnClickListenerImpl ();} private class OnClickListenerImpl implements OnClickListener {@ Overridepublic void onClick (View v) {new Thread () {public void run () {mActivity. runOnUiThread (new Runnable () {@ Overridepublic void run () {mTextView. setText ("My name is zxc, number is 007 ");}});};}. start ();}}}
Main. xml is as follows: