activity的runOnUiThread方法使用
本文出自:http://www.androidkaifa.com/forum.php?mod=viewthread&tid=221&page=1&extra=#pid269
我们都知道在android系统中我们是不能在UI线程外更新界面的,如果你要想在一个UI线程外更新UI的话,你得用那Handler啊,或是异步线程类等一些方式,下面www.androidkaifa.com就会大家讲解一个很简单,却很实用的方法让UI在一个“用户线程”中更新,直接用acitivty类的runOnUiThread(runnable run)方法,
本实例通过一个界面每五秒换一个文字来实现那道理,
不多说直接上代码,
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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
tools:context=".TimerThreadExample"
android:textSize="40pt" />
</RelativeLayout>
二:主activity类代码:
public class ThreadExample extends Activity {
protected int splashTime = 3000;
TextView tv1;
String[] name = {"A","N","D","R","O","I","D"};
int timer =0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.textView1);
Thread th=new Thread(){
@Override
public void run(){
try
{
for (timer = 0; timer < 7; timer++)
{
int waited = 0;
while(waited < splashTime)
{
Thread.sleep(100);
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
tv1.setText(name[timer]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
waited += 100;
}
}
}catch (InterruptedException e) {
}
}
};
th.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
运行结果如下:

- 1楼geyubin昨天 17:25
- [code=java]n final Handler mHandler = new Handler();n public final void runOnUiThread(Runnable action) {n if (Thread.currentThread() != mUiThread) {n mHandler.post(action);n } else {n action.run();n }n }n[/code]nngoogle没有开放代码,直接让你获取activity里面定义的Handler,本质还是交给UI线程里面的handler去执行业务逻辑