gpt4 book ai didi

android - 如何使更新进度中的ProgressBar "smoother"

转载 作者:行者123 更新时间:2023-11-29 21:07:48 26 4
gpt4 key购买 nike

如何让 ProgressBar 显示进度更流畅?

目前我正在使用它(它以秒为单位计算到指定时间,在此示例中 secondsToRun = 120):

public void startBrushing(View view) {
progressBar = (ProgressBar) findViewById(R.id.progressBar);

int secondsToRun = 120;
progressBar.setMax(secondsToRun);

runner = new AsyncTaskRunner();
runner.execute(secondsToRun);
}

private class AsyncTaskRunner extends AsyncTask<Integer, Integer, Void> {

private String resp;

@Override
protected Void doInBackground(Integer... params) {
try {
for(int i = 0; i <= params[0]; i++) {
publishProgress(i);
Thread.sleep(1000);

if (i == params[0]) {
Log.d("CyCy", "Finished Countdown!");
chronometer.stop();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}

return null;
}

@Override
protected void onProgressUpdate(Integer... status) {
progressBar.setProgress(status[0]);
}
}

如果我增加更新时间(secondsToRun = 1200 并且每 100 毫秒更新一次,而不是每 1000 毫秒更新一次)它也能正常工作,但会有点不准确。

如果我使用 secondsToRun = 12000 并每 10 毫秒更新一次,那将非常不准确。当循环实时显示“30 秒完成”时,它是 37 秒。

感谢您的帮助,抱歉我的英语不好。

最佳答案

正如我在上面的评论中所建议的那样,您可以根据实时而不是您自己的计数器来更新 ProgressBar:

我还没有测试过这个,所以把它看作是温和的伪代码:

private class AsyncTaskRunner extends AsyncTask<Void, Long, Void> {

private long startTime;
private long progressDurationMillis;
private long updateFrequencyMillis = 200; // default 0.2 secs

// pass in the progress bar max duration in the constructor
// so you can set the dialog max value in onPreExecute()
public AsyncTaskRunner(long progressDurationMillis) {
this.progressDurationMillis = progressDurationMillis;
}

// a second constructor for easy testing of different update values
// you could test a bunch together in a loop and see which looks best
public AsyncTaskRunner(long progressDurationMillis, long updateFrequencyMillis) {
this(progressDurationMillis);
this.updateFrequencyMillis = updateFrequencyMillis;
}

@Override
public void onPreExecute() {
this.startTime = System.getCurrentMillis();
// set up your dialog here and display
}

@Override
protected Void doInBackground(Void... params) {
long timeExpired = 0;
try {
while(true) {
timeExpired = progressDurationMillis - (System.getCurrentMillis() - startTime)
publishProgress(timeExpired);
Thread.sleep(updateFrequencyMillis);

if (timeExpired >= progressDurationMillis) {
Log.d("CyCy", "Finished Countdown!");
chronometer.stop();
// exit the while loop
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onProgressUpdate(Long... status) {
progressBar.setProgress(status[0]);
}

@Override
public void onPostExecute() {
// dismiss your dialog here
}
}

关于android - 如何使更新进度中的ProgressBar "smoother",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23953707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com