我正在通过一本书学习,它给了我这个例子:
Handler handler=new Handler() {
@Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
}
};
和
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning.get();i++) {
Thread.sleep(500);
handler.sendMessage(handler.obtainMessage());
}
} catch (Throwable t) {
// just end the background thread
}
}
});
哪个效果很好.但是,在书中进一步说,它说:
If you would rather not fuss with Message objects, you can also pass
Runnable objects to the Handler, which will run those Runnable
objects on the activity UI thread. …you can use those same methods
on any View (i.e., any widget or container). This slightly simplifies
your code, in that you can then skip the Handler object.
但是没有给出如何通过Runnable对象执行此操作的示例.有人有例子吗?
解决方法:
像这样的东西:
Handler h = new Handler();
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning.get();i++) {
Thread.sleep(500);
handler.post(new Runnable() {
public void run() {
bar.incrementProgressBy(5);
}
});
}
}
catch (Throwable t) {
// just end the background thread
}
}
});