在执行AsyncTask时,Android自定义进度指示器

时间:2013-02-26 09:48:21

标签: android android-asynctask progress

运行AsyncTask时,我想显示进度指示器。这个库存很难看,所以我用自己的布局做了一个布局。然而,问题在于它是一个单独的布局,这意味着我需要一个新的活动来显示它。

我以为我可以启动活动(~progressActivity~)然后......销毁它?但似乎不可能阻止父母的儿童活动。

我可以在AsyncTask-invoking-activity上隐藏进度指示器,然后在处理时让它显示并隐藏其余的布局。现在我需要在我的主布局中使用两个子布局,并且每次都隐藏其中一个子布局。这听起来像是一个黑客,我不太喜欢它。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

如果您需要更多地控制ProgressBar,可以使用WindowManager在所有内容之上添加视图。它可以在没有任何额外布局,活动或窗口的情况下完成。您可以像常规视图一样控制动画,触摸,位置和可见性。完全正常工作的代码:

final ProgressBar view = new ProgressBar(TestActivity.this);
view.setBackgroundColor(0x7f000000);
final LayoutParams windowParams = new WindowManager.LayoutParams();
windowParams.gravity = Gravity.CENTER;
windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
windowParams.format = PixelFormat.TRANSLUCENT;
windowParams.windowAnimations = 0;

new AsyncTask<Integer, Integer, Integer>() {
    public void onPreExecute() {
        // init your dialog here;
        getWindowManager().addView(view, windowParams);
    }

    public void onPostExecute(Integer result) {
        getWindowManager().removeView(view);
        // process result;
    }

    @Override
    protected Integer doInBackground(Integer... arg0) {
        // do your things here
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}.execute();

答案 1 :(得分:0)

new AsyncTask<Params, Progress, Result>() {
   Dialog dlg = new Dialog();
   View customProgress;
   public void onPreExecute() {
       //init your dialog here;
       View customProgress = LayoutInflater.from(CurrentActivity.this).inflate(R.layout.your_progress_layout, null, false);
       dialog.setContentView(view);
       dialog.show();
   }
   public Result doInBackground(Params... params) {
    // do something
    publishProgress(progress);  
   }
   public void onProgressUpdate(Progress progress) {
    // do something with progressView;
   }
   public void onPostExecute(Result result) {
      dlg.dissmiss();
      // process result;
   }
}.execute();

这是可行的方法(只有样本,可能包含错误)