非常简洁的代码:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
((TextView) findViewById(R.id.button1)).setText("子线程更新ui");
}
});
}
}).start();
}
}
使用Handler的Post方法,传递一个Runnable的对象,post方法在android api文档中是这么描述的:
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
也就是说子线程把更新ui的操作通过handler传递给ui线程,然后会被自动执行,更新ui就这么愉快的被完成啦~!