问题
How can I edit the views of an activity from an AsyncTask BEFORE the task is complete? I cannot access any of the views from the doInBackground method, and I do not want to wait until the task has completed. Is there a way to go about doing this? Or do I have to create a thread within the doInBackground (which sounds to me would be bad practice) and then access the view on that thread's completion?
回答1:
Override this method:
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
Call it in doInBackground()
of your AsyncTask. This method publishProgress(Progress... values)
happens on the UI thread when you call it from doInBackground()
.
For more information, read AsyncTask
回答2:
You could define the class MyAsyncTask
containing the following:
private final ProgressDialog progressDialog;
public MyAsyncTask(Context context) {
super(context);
progressDialog = new ProgressDialog(context);
progressDialog.setTitle(R.string.title);
progressDialog.setButton(
DialogInterface.BUTTON_NEGATIVE,
context.getResources().getString(R.string.abort),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MyAsyncTask.this.cancel(true);
progressDialog.dismiss();
}
}
);
progressDialog.show();
}
@Override
protected void onProgressUpdate(String... params) {
progressDialog.setMessage(params[0]);
}
You can then use the ProgressDialog
to report back to the GUI, e.g., by calling publishProgress("TEST")
.
回答3:
You can update the UI from onProgressUpdate()
. There is a tricky way, you can send some integer or boolean value to progress update and change your UI according to the condition.
@Override
protected void onProgressUpdate(Integer... values) {
if(values[0] == 1) {
// update the UI
button.settext("updating");
}
}
You can call onProgressUpdate fram asynctask by calling
publishProgress(1);
Hope this works, try out.
回答4:
You need to override this method inside your AsynTask Class:
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
ProgressBar bar = (ProgressBar) findViewById(R.id.prgLoading);
bar.setIndeterminate(true);
super.onProgressUpdate(values);
}
You can define a progress bar as I show in here and set some value into it.
来源:https://stackoverflow.com/questions/25182211/updating-ui-during-asynctask