Ways of Update Android UI

原文:zhangxiaowei

总结:

1.Activity的runOnUiThread()和 View.post(Runnable r)在本质上都是调用Handler的post()方法处理;
2.在子线程中直接更新UI,可以使用 Handler的post(),Activity的runOnUiThread()和 View.post(Runnable r)这三种方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
private void updateUiByHandler() {
new Thread() {
@Override
public void run() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = new Message();//mMyHandler.obtainMessage()
message.what = MSG_WHAT;
message.obj = "来自子线程的数据";
mMyHandler.sendMessage(message);
}
}.start();
}
private void updateUiByHandlerPost() {
new Thread() {
@Override
public void run() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mMyHandler.post(new Runnable() {
@Override
public void run() {
tv.setText(" Handler.post更新UI");
}
});
}
}.start();
}
private void updateUiByRunOnUiThread(){
new Thread(){
@Override
public void run() {
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText("runOnUiThread更新UI");
}
});
}
}.start();
}
private void updateUiByViewPost(){
new Thread(){
@Override
public void run() {
super.run();
tv.post(new Runnable() {
@Override
public void run() {
tv.setText("view post更新UI");
}
});
}
}.start();
}

参考阅读

Android 源码解析Handler处理机制(一)
Android 源码解析Handler处理机制(二)
你不知道的Runnable接口,深度解析Runnable接口
Android 源码解析AsyncTask(一)
Android 源码解析AsyncTask(二)