如何每2秒更改ProgressDialog的消息?

时间:2017-11-09 06:16:25

标签: java android

我有ProgressDialog,我想每隔 2秒更改消息。在此代码中,我将进度时间设置为 10秒。所以我想让它有 5条消息

private void showProgressDialog() {

    progressDialog = new ProgressDialog(this, getProgressDailogStyle());
    progressDialog.setMessage("Processing ...");
    progressDialog.show();
    progressDialog.setCancelable(false);

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            progressDialog.dismiss();
            mInterstitialAd.show();
        }
    }, 10000);
}

5 个答案:

答案 0 :(得分:3)

您可以使用CountDownTimer

    count = 0;
    progressDialog = new ProgressDialog(this, getProgressDailogStyle());
    progressDialog.setMessage("Processing ...");
    progressDialog.show();
    progressDialog.setCancelable(false);

    new CountDownTimer(10000, 2000) {

        public void onTick(long millisUntilFinished) {
            //here you can have your logic to set message
            count=count+1;
            if (count==1){
                progressDialog.setMessage("Processing 1");
            }else if (count==2){
                progressDialog.setMessage("Processing 2");
            } 
              // until the count = 5 


        }

        public void onFinish() {
            //the progress is finish
            count = 0;
            progressDialog.dismiss();

        }

    }.start();

答案 1 :(得分:0)

在代码中使用Timer。并设置schedule方法的时间。

schedule方法中。

  • 第一个参数是TimerTask
  • 第二个参数是delay时间
  • 第三个参数是period时间

试试这个。

private void showProgressDialog() {

    progressDialog = new ProgressDialog(this, getProgressDailogStyle());
    progressDialog.setMessage("Processing ...");
    progressDialog.show();
    progressDialog.setCancelable(false);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            // do something
            Message message=new Message();  
            message.what=0;  
            mHandler.sendMessage(message);  
        }
    }, 0, 2000);
}

<强>更新

private Handler mHandler = new Handler(){  
    @Override  
    public void handleMessage(Message msg) {  

        // TODO Auto-generated method stub  
        if(msg.what == 0){  
            //change message
        }  
    }     
};  

答案 2 :(得分:0)

Runnable r = new Runnable() {
    public void run({
        progressDialog.setMessage('...your msg...');
        handler.postDelayed(r,2000)
    })
};
handler.postDelayed(r,2000);

答案 3 :(得分:0)

尝试下面的代码,setMessage必须在runOnUiThread,

public void setMessage(String message) {
    if (dialog != null && dialog.isShowing()) {
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.setMessage(message);
            }
        });
    }
}

答案 4 :(得分:0)

由于您已经在运行处理程序,因此您可以轻松地向UI线程显示消息,即ProgressDialog。而不是运行10 sec延迟的处理程序,在5 interval的循环中运行它,即{{ 1}}像这样延迟。

2 sec