我的Activity中有一个进度条(ProgressBar)。当启动Activity时,我会检查从另一个地方获取的值,并更新到进度条中。以下是我的代码:
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar_detail);
final TextView progressText = (TextView) findViewById(R.id.progressText_detail);
final ImageView btnCancel = (ImageView) findViewById(R.id.imgCancel_detail);
progressBar.setVisibility(View.VISIBLE);
progressText.setVisibility(View.VISIBLE);
btnCancel.setVisibility(View.VISIBLE);
Thread t = new Thread() {
public void run() {
((Activity) ctx).runOnUiThread(new Runnable() {
public void run() {
int oldProgress = 0;
while (progressBar.getProgress() < 100) {
int value = Downloader.progress.get(gameId+ "");
if (value != oldProgress) {
oldProgress = value;
progressBar.setProgress(value);
progressText.setText(value + " %");
}
}
}
});
}
};
t.start();
我从int value = Downloader.progress.get(gameId)
获取到的ProgressBar的值是正确的。但当我运行这段代码时,活动没有响应,也没有显示任何东西(但应用程序没有崩溃)。似乎更新ProgressBar的线程正在运行并阻塞UI线程,因此活动布局未显示。
我的代码有什么问题?在这种情况下更新ProgressBar的正确方法是什么?