为什么android中的UI视图更新不能放在子线程中

2024-11-28 11:50:14
推荐回答(1个)
回答(1):

解决方案如下:
public void run() {
while(progress<100){
progress = progress + 1;
try {
textView.setText(progress+"%");//这边异常
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} 异常代码:
Only the original thread that created a view hierarchy can touch its views

public class ClicktextApp extends Activity {
private Thread myRefreshThread = null;
private ClickText ct = null;
protected static final int GUIUPDATEIDENTIFIER = 0x101; // 自定义Handler 继随自Handler,需要实现handleMessage方法,用以接受消息!
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {//处理消息
switch (msg.what) {
case ClicktextApp.GUIUPDATEIDENTIFIER:
ct.invalidate();// 更新视图UI
break;
}
super.handleMessage(msg);
}
}; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ct = new ClickText(this);///////自定义的VIEW
setContentView(ct);
new Thread(new myThread()).start();// 启动线程 } class myThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) { Message message = new Message();// 生成消息,并赋予ID值
message.what = ClicktextApp.GUIUPDATEIDENTIFIER;
myHandler.sendMessage(message);// 投递消息
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}}