我正在为 Android 进行测验,我想要在有限的时间内回答每个问题。所以我想在答案下显示一个进度条,从 5 到 0(秒)倒计时。当它达到零时我想做一些事情。我有测验并且一切正常,我只想添加进度栏。
提前致谢!
您可以在 Android 中使用倒计时器。
这是一个您可以参考的示例单击此处
您可以在您的 Activity 中使用下面的 ProgressBar。
<ProgressBar
android:id="@+id/progressbar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:progress="0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/bottom_header_relativelayout"
/>
在您的活动中使用
CountDownTimer
就像下面的代码。
ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
int i=0;
mProgressBar=(ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setProgress(i);
mCountDownTimer=new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i+ millisUntilFinished);
i++;
mProgressBar.setProgress((int)i*100/(5000/1000));
}
@Override
public void onFinish() {
//Do what you want
i++;
mProgressBar.setProgress(100);
}
};
mCountDownTimer.start();
您可以使用
ObjectAnimator
来动画化 ProgressBar
的进度:
ObjectAnimator animation = ObjectAnimator.ofInt(pb, "progress", 0, 100);
animation.setDuration(5000);
animation.setInterpolator(new DecelerateInterpolator());
animation.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) { }
@Override
public void onAnimationEnd(Animator animator) {
//do something when the countdown is complete
}
@Override
public void onAnimationCancel(Animator animator) { }
@Override
public void onAnimationRepeat(Animator animator) { }
});
animation.start();
无需 XML 声明
ProgressDialog TempDialog;
CountDownTimer CDT;
int i =5;
TempDialog = new ProgressDialog(Your_Class_Name.this);
TempDialog.setMessage("Please wait...");
TempDialog.setCancelable(false);
TempDialog.setProgress(i);
TempDialog.show();
CDT = new CountDownTimer(5000, 1000)
{
public void onTick(long millisUntilFinished)
{
TempDialog.setMessage("Please wait.." + i + " sec");
i--;
}
public void onFinish()
{
TempDialog.dismiss();
//Your Code ...
}
}.start();
你可以尝试一下这个例子,它是从100到0倒计时并显示在ProgressBar中。
val maxSecond = 60L val timerBar = viewForm.findViewById<ProgressBar>(R.id.pb_timer) timerBar.max = 100 timerBar.progress = 100 var distinct = 0.0f object : CountDownTimer(1000 * maxSecond, 1000) { override fun onTick(millisUntilFinished: Long) { val second = (millisUntilFinished / 1000.0f).roundToInt() val unit = (second.toFloat() / 100f) if(distinct == 0f){ distinct = 100f / unit } val cal = unit * distinct timerBar.progress = cal.toInt() } override fun onFinish() { Log.d("check", "done!") } }.start()