Handler詳解系列(七)——Activity.runOnUiThread()方法詳解,runonuithread
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;@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如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="test" android:layout_centerHorizontal="true" android:layout_marginTop="50dip" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:layout_centerHorizontal="true" android:layout_marginTop="120dip" /> <TextView android:id="@+id/tipTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="測試在子線程中更新UI" android:layout_centerInParent="true" /></RelativeLayout>
八字命宮詳解——本人姓謝 男 生於1989年9月初五晚上七點半(農曆),
從小克父,最好離祖地發展。有興趣hi聊。