看到应用程序有两个按钮。一个启动三十秒计时器,另一个启动六十秒计时器。启动计时器没有问题。问题是,假设我点击了 60 秒按钮,然后立即点击 30 秒按钮,textview 在从 60 到 0 和 30 到 0 倒计时之间切换。它变成 59 28 57 26 等等..我想要什么要知道的是,假设我先点击 60 秒,然后点击 30 秒按钮,我希望取消 60 秒倒计时并开始 30 秒倒计时。
这是我的代码。我只发布相关的部分。
[编辑]我现在已经发布了整个代码。
package com.android.tapme;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TapMe extends Activity {
private int countValue = 0, psuedoCountValue = 0;
private TextView textView1;
private TextView textView2;
Button tapButton;
Button sixty_seconds;
Button thirty_seconds;
private boolean thirtyon=false, sixtyon=false;
boolean timeUp=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tap_me);
tapButton= (Button) findViewById(R.id.tapButton);
textView1 = (TextView) findViewById(R.id.textView1);
textView1.setTextSize(40);
textView2 = (TextView) findViewById(R.id.textView2);
textView2.setTextSize(20);
thirty_seconds = (Button) findViewById(R.id.thirty_seconds);
sixty_seconds= (Button) findViewById(R.id.sixty_seconds);
sixty_seconds.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
timeUp=false;
countValue=0;
sixtyon=true;
checkTapValue();
MyCount myCount=new MyCount(60000,1000);
if(thirtyon==true)
{
myCount.cancel();
}
myCount=new MyCount(60000,1000);
thirtyon=false;
myCount.start();
}
});
thirty_seconds.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
timeUp=false;
countValue=0;
thirtyon=true;
checkTapValue();
MyCount myCount=new MyCount(30000,1000);
if(sixtyon==true)
{
myCount.cancel();
}
myCount=new MyCount(30000,1000);
sixtyon=false;
myCount.start();
}
});
}
private void checkTapValue() {
tapButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(timeUp==false)
{
countValue++;
textView1.setText(Integer.toString(countValue));
}
else if(timeUp==true)
{
psuedoCountValue=countValue;
textView1.setText(Integer.toString(psuedoCountValue));
}
}
});
}
public void disable_Button()
{
timeUp=true;
psuedoCountValue=countValue;
}
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
disable_Button();
textView2.setText("Time's up!");
}
@Override
public void onTick(long millisUntilFinished) {
System.out.println(millisUntilFinished);
textView2.setText("" + (int) (millisUntilFinished / 1000));
}
}
}