MainActivity例如以下:
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描写叙述: * 在子线程中更改UI的方式三 * * 调用Activity.runOnUiThread(Runnable runnable)方法. * *该方法的源代码例如以下: * * 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(); * } * } * * * 源代码中的这段凝视太具体和贴心了,赞一个! * 在UI线程中运行该Runnable. * 假设当前线程是UI线程,那么该Runnable会马上运行. * 假设当前的线程不是UI线程则调用UI线程handler的post()方法将其放入UI线程的消息队列中. * 注意:勿在runOnUiThread(Runnable runnable)中做耗时操作 * * 參考资料: * 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; @Override protected 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 { @Override public void onClick(View v) { new Thread(){ public void run() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { mTextView.setText("My name is zxc , number is 007"); } }); }; }.start(); } } }main.xml例如以下: