我正在制作一个课程项目,对于这个项目,我需要显示一个倒数计时器。将有一个按钮,使计时器增加5秒以上。例如,如果计时器在1:00设置并启动,并且用户单击该按钮,则计时器必须像1:05一样增加+5。
我的代码:
public class MainActivity extends Activity {
Button incrementTime, startTime;
public TextView timedisplay;
long millisInFuture = 1000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
incrementTime = (Button) findViewById(R.id.button2);
startTime = (Button) findViewById(R.id.button3);
timedisplay = (TextView) findViewById(R.id.mycounter);
resetText();
incrementTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
millisInFuture += 1000;
resetText();
}
});
startTime.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
CountDownTimer wavetimer = new myTimer(millisInFuture + 3000, 1000).start();
// ^ add 3 seconds.
}
});}
protected void resetText() {
timedisplay.setText("Time Left: " + millisInFuture / 1000);
}
public class myTimer extends CountDownTimer {
private long millisActual;
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
millisActual = millisInFuture - 3000;
}
@Override
public void onTick(long millisUntilFinished) {
//v start showing the tick after 3 seconds.
if (millisUntilFinished <= millisActual) {
timedisplay.setText("Time Left: " + millisUntilFinished / 1000);
}
}
@Override
public void onFinish() {
timedisplay.setText("Countdown Finished");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
我的问题:
这与我想要的方式相同,但它只在定时器运行完毕后递增。我希望它在倒计时运行期间递增!
答案 0 :(得分:0)
您可以根据自己的需要使用此课程:
public abstract class MyCountDownTimer {
private CountDownTimer cdt;
private long millisInFuture;
private long countDownInterval;
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
this.millisInFuture = millisInFuture;
this.countDownInterval = countDownInterval;
recreateCounter(millisInFuture, countDownInterval);
}
public abstract void onFinish();
public abstract void onTick(long millisUntilFinished);
public void start(){
cdt.start();
}
private void setMillisInFuture(long millisInFuture){
this.millisInFuture = millisInFuture;
}
public void onIncrement(long millis){
millisInFuture += millis;
recreateCounter(millisInFuture, countDownInterval);
}
private void recreateCounter(long millisInFuture, long countDownInterval){
if(cdt != null){
try {
cdt.cancel();
} catch (Exception e) {
}
}
cdt = new CountDownTimer(millisInFuture, countDownInterval) {
@Override
public void onTick(long millisUntilFinished) {
setMillisInFuture(millisUntilFinished);
MyCountDownTimer.this.onTick(millisUntilFinished);
}
@Override
public void onFinish() {
MyCountDownTimer.this.onFinish();
}
};
}
}