asyncTask中的ProgressDialog setProgress和setMessage不起作用 [英] ProgressDialog setProgress and setMessage inside asyncTask don't work
问题描述
我有一个asynktask,它显示一个progressDialog并在doInBackground方法中更新它的值.方法代码:
I have asynktask that shows a progressDialog and update its value in doInBackground method. the methods code:
@Override
protected void onPreExecute() {
progress = new ProgressDialog(cont);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setTitle(cont.getResources().getString(R.string.pleaseWait));
progress.setMessage(cont.getResources().getString(R.string.loadingImages));
progress.show();
super.onPreExecute();
}
@Override
protected String doInBackground(Void... arg0) {
progress.setProgress(2);
//do some work on the database and network
progress.setProgress(25);
//Do some extra work
for(int i = 0; i < itemImagesList.size(); i++){
publishProgress((int) ((i / (float) itemImagesList.size()) * 100));
//Do somework
}
}
@Override
protected void onProgressUpdate(Integer... prog) {
progress.setProgress(prog[0]);
}
@Override
protected void onPostExecute(String result) {
progress.dismiss();
super.onPostExecute(result);
}
progressDialog值完全不变!如果我尝试使用以下方法设置对话框消息:
The progressDialog value doesn't change at all! and if I tried to set the dialog message using:
progress.setMessage("At item "+i);
如果我将其放在方法的中间会发生一些异常,但是在第一个中它可以正常工作!
some exception occurs if I put it in the middle of the method, but in the first it works fine!
怎么了?
推荐答案
您的问题与setIndeterminate(true);
有关,如果要进行进度更新,则应将其设置为false
(请参阅
Your issue is related to setIndeterminate(true);
You should set it to false
if you want to have progress update (take a look at Android setProgress doc), don't forget to also use setMax()
to set progress max value to the desired one.
正如洛朗所说,您只能在UI线程上更改进度,因此您必须在onProgressUpdate
中而不是在doInBackground
And as said Laurent you can change progress only on UI thread so you have to do it in onProgressUpdate
and not in doInBackground
这篇关于asyncTask中的ProgressDialog setProgress和setMessage不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!