我正在關注this tutorial 以瞭解如何製作進度條。我試圖在我的活動之上顯示進度條,並讓它在後臺更新活動的表格視圖。從異步任務更新表android
所以我創建了對話的異步任務,需要一個回調:
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.
}
}
但是這給了我同步錯誤。任何想法如何,我可以顯示進度,並在同一時間更新我的表中的背景是什麼?
目前我的UI看起來像: