如何在最小延迟后显示ProgressBar?

Jef*_*rod 5 android android-progressbar android-asynctask progress-bar

我有一个AsyncTask不确定的ProgressBar,通常很快就会执行,但偶尔会很慢.当没有可辨别的等待时,进度条快速闪烁是不可取的并且分散注意力.

有没有办法延迟显示进度条而不创建另一个嵌套AsyncTask

Jef*_*rod 3

感谢Code Droid,我能够编写一个抽象AsyncTask类,在指定的延迟后显示不确定的进度条。只需扩展此类,而不是AsyncTask并确保super()在适当时调用:

public abstract class AsyncTaskWithDelayedIndeterminateProgress
      <Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
   private static final int MIN_DELAY = 250;
   private final ProgressDialog progressDialog;
   private final CountDownTimer countDownTimer;

   protected AsyncTaskWithDelayedIndeterminateProgress(Activity activity) {
      progressDialog = createProgressDialog(activity);
      countDownTimer = createCountDownTimer();
   }

   @Override protected void onPreExecute() {
      countDownTimer.start();
   }

   @Override protected void onPostExecute(Result children) {
      countDownTimer.cancel();
      if(progressDialog.isShowing())
         progressDialog.dismiss();
   }

   private ProgressDialog createProgressDialog(Activity activity) {
      final ProgressDialog progressDialog = new ProgressDialog(activity);
      progressDialog.setIndeterminate(true);
      return progressDialog;
   }

   private CountDownTimer createCountDownTimer() {
      return new CountDownTimer(MIN_DELAY, MIN_DELAY + 1) {
         @Override public void onTick(long millisUntilFinished) { }

         @Override public void onFinish() {
            progressDialog.show();
         }
      };
   }
Run Code Online (Sandbox Code Playgroud)