案例:我在活动中有一个按钮和列表视图。单击按钮时,我添加了一个单击侦听器,它启动了一个新线程,我在其中更新进度条。工作完成后,即进度条完成 100%,我想更新列表视图。
final OnClickListener mStartScan = new OnClickListener() {
@Override
public void onClick(View v) {
// prepare for a progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(false);
progressBar.setMessage(getString(R.string.text_scanning_inbox));
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(totalSms);
progressBar.show();
progressBarStatus = 0;
Thread progressThread = new Thread(new Runnable() {
public void run() {
while (progressBarStatus < totalSms) {
// process some tasks
progressBarStatus = someStuff();
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= done) {
// sleep 1 seconds, so that you can see the 100%
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
// this method updates the list
populateList();
}
}
});
progressThread.start();
// try {
// progressThread.join();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } finally {
// populateList();
// }
}
};
问题:当我在完成任务并关闭进度条后更新列表视图时,我得到一个异常,它说视图只能从创建它的线程更新。
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
我还尝试了什么:我尝试等待正在运行进度条的线程完成,然后从主线程更新列表视图。
try {
progressThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
populateList();
}
但是,这不起作用。它根本不显示进度条。