我在android中有一个水平进度条。我需要在60秒内完成它。
为什么以下代码不起作用?
int progress = 0;
progressBarHorizontal.setMax(60);
while(progress < 60) {
progressHandler.postDelayed((new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
}),progress * 1000);
progress++;
}
请提出其他一些方法。我试过这个:
new Thread(new Runnable() {
int progress = 0;
public void run() {
long timerEnd = System.currentTimeMillis() + 60 * 1000;
while (timerEnd > System.currentTimeMillis() ) {
progress = (int) (timerEnd - System.currentTimeMillis()) / 1000;
// Update the progress bar
progressHandler.post(new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.w("tag","Progress thread cannot sleep");
}
}
}
}).start();
但它也没有用。
第二段代码实际上有效,问题在于我的逻辑。
答案 0 :(得分:5)
您可以尝试CountDownTimer
:
pd = ProgressDialog.show(MovementEntry.this, "", "Please Wait...",
true, false);
pd.show();
new CountDownTimer(60000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
//this will be done every 1000 milliseconds ( 1 seconds )
int progress = (60000 - millisUntilFinished) / 1000;
pd.setProgress(progress);
}
@Override
public void onFinish() {
//the progressBar will be invisible after 60 000 miliseconds ( 1 minute)
pd.dismiss();
}
}.start();
答案 1 :(得分:3)
这个会更新状态栏,直到达到最大值:
private int progress = 0;
private final int pBarMax = 60;
...
final ProgressBar pBar = (ProgressBar) findViewById(R.id.progressBar1);
pBar.setMax(pBarMax);
final Thread pBarThread = new Thread() {
@Override
public void run() {
try {
while(progress<=pBarMax) {
pBar.setProgress(progress);
sleep(1000);
++progress;
}
}
catch(InterruptedException e) {
}
}
};
pBarThread.start();
答案 2 :(得分:2)
您可以尝试使用此代码:
Thread timer = new Thread(){
public void run(){
try{
sleep(10000);
while(progressBarStatus < 10000){
StartPoint.this.runOnUIThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
}
}
};
timer.start();
答案 3 :(得分:1)
此代码适用于我
new Thread(new Runnable() {
public void run() {
long timerEnd = System.currentTimeMillis() + 60 * 1000;
while (timerEnd > System.currentTimeMillis()) {
progress = 60 - (int) (timerEnd - System.currentTimeMillis()) / 1000;
// Update the progress bar
progressHandler.post(new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.w("App","Progress thread cannot sleep");
}
}
progressHandler.post(new Runnable() {
public void run() {
okButton.performClick();
}
});
}
}).start();