[英]How to change message of ProgressDialog every 2 seconds?
我有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);
}
您可以使用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();
在代碼中使用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
}
}
};
Runnable r = new Runnable() {
public void run({
progressDialog.setMessage('...your msg...');
handler.postDelayed(r,2000)
})
};
handler.postDelayed(r,2000);
嘗試下面的代碼,並且setMessage必須在runOnUiThread中,
public void setMessage(String message) {
if (dialog != null && dialog.isShowing()) {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.setMessage(message);
}
});
}
}
由於您已經在運行處理程序,因此可以輕松地向UI線程(即ProgressDialog)顯示消息。與其以10 sec
延遲運行處理程序,還不如將其以5 interval
(即2 sec
延遲)循環運行。
private int count = 1;
Runnable runnable = null;
private void showProgressDialog() {
progressDialog = new ProgressDialog(this, getProgressDailogStyle());
progressDialog.setMessage("Processing ...");
progressDialog.show();
progressDialog.setCancelable(false);
final Handler handler = new Handler();
runnable = new Runnable() {
public void run() {
Log.i("message",""+counter);
if (counter == 5) {
handler.removeCallbacks(runnable);
progressDialog.dismiss();
// mInterstitialAd.show();
}else {
progressDialog.setMessage("your message");
handler.postDelayed(runnable, 2000);
counter++;
}
}
};
handler.post(runnable);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.