我正在按照本教程 学习如何制作进度条。我试图在我的活动顶部显示进度条,并让它在后台更新活动的表格视图。
所以我为接受回调的对话框创建了一个异步任务:
package com.lib.bookworm;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class UIThreadProgress extends AsyncTask<Void, Void, Void> {
private UIThreadCallback callback = null;
private ProgressDialog dialog = null;
private int maxValue = 100, incAmount = 1;
private Context context = null;
public UIThreadProgress(Context context, UIThreadCallback callback) {
this.context = context;
this.callback = callback;
}
@Override
protected Void doInBackground(Void... args) {
while(this.callback.condition()) {
this.callback.run();
this.publishProgress();
}
return null;
}
@Override protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.incrementProgressBy(incAmount);
};
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
dialog.setProgress(0);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(maxValue);
dialog.show();
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
this.callback.onThreadFinish();
}
}
在我的活动中:
final String page = htmlPage.substring(start, end).trim();
//Create new instance of the AsyncTask..
new UIThreadProgress(this, new UIThreadCallback() {
@Override
public void run() {
row_id = makeTableRow(row_id, layout, params, matcher); //ADD a row to the table layout.
}
@Override
public void onThreadFinish() {
System.out.println("FINISHED!!");
}
@Override
public boolean condition() {
return matcher.find();
}
}).execute();
因此,上面创建了一个异步任务来运行以更新表格布局活动,同时显示显示已完成工作量的进度条。
但是,我收到一条错误消息,说只有启动活动的线程才能更新其视图。我尝试将异步任务的运行更改为以下内容:
MainActivity.this.runOnUiThread(new Runnable() {
@Override public void run() {
row_id = makeTableRow(row_id, layout, params, matcher); //ADD a row to the table layout.
}
}
但这给了我同步错误。有什么想法可以显示进度并同时在后台更新我的表格吗?
目前我的用户界面看起来像: