android应用程序上的倒计时

android应用程序上的倒计时,android,timer,Android,Timer,我想做一个简单的测验来练习。我无法添加倒计时计时器。如果没有回答任何问题,它可以正常工作,但是当我回答一个问题时,即使它是正确的或错误的,计时器也不会重置。我在developer.android.com上看到了cancel方法,但我无法让它工作。有什么帮助吗 这是我的密码。任何关于更好代码的建议都是受欢迎的,但我尽量保持简单,因为我是android开发新手 public class QuizActivity extends Activity implements OnClickListener{

我想做一个简单的测验来练习。我无法添加倒计时计时器。如果没有回答任何问题,它可以正常工作,但是当我回答一个问题时,即使它是正确的或错误的,计时器也不会重置。我在developer.android.com上看到了cancel方法,但我无法让它工作。有什么帮助吗

这是我的密码。任何关于更好代码的建议都是受欢迎的,但我尽量保持简单,因为我是android开发新手

public class QuizActivity extends Activity implements OnClickListener{
int MAX_Q = 6; 
List<Question> quesList;
int score=0;
int lives=3;
int qid=0;
Question currentQ;
TextView txtQuestion, TextViewTime;
Button ansA, ansB, ansC;

private MediaPlayer mpCorrect;
private MediaPlayer mpWrong;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);         
        DbHelper db=new DbHelper(this);     
        quesList=db.getAllQuestions();  
        currentQ=quesList.get(qid);     
        txtQuestion=(TextView)findViewById(R.id.questionTextView);
        ansA = (Button)findViewById(R.id.ans1);
        ansB=(Button)findViewById(R.id.ans2);
        ansC=(Button)findViewById(R.id.ans3);       
        ansA.setOnClickListener(onClickListener);
        ansB.setOnClickListener(onClickListener);
        ansC.setOnClickListener(onClickListener);                       
        mpCorrect = MediaPlayer.create(this, R.raw.correct);
        mpWrong = MediaPlayer.create(this, R.raw.wrong);            
        setQuestionView();  

    }

    public class CounterClass extends CountDownTimer{

        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;          
            String secs = String.format("00:%02d", TimeUnit.MILLISECONDS.toSeconds(millis));
            TextViewTime.setText(secs);

        }

        @Override
        public void onFinish() {
            wrongAnswer();

        }

    }

    private OnClickListener onClickListener = new OnClickListener() {
         @Override
         public void onClick(final View v) {
             switch(v.getId()){
                 case R.id.ans1:
                     if(currentQ.getANSWER().equals(ansA.getText()))
                         correctAnswer();
                     else
                         wrongAnswer();
                 break;
                 case R.id.ans2:
                     if(currentQ.getANSWER().equals(ansB.getText()))
                         correctAnswer();
                     else
                         wrongAnswer();
                 break;
                 case R.id.ans3:
                     if(currentQ.getANSWER().equals(ansC.getText()))
                         correctAnswer();
                     else
                         wrongAnswer();
                 break;
             }

       }
    };


    private void setQuestionView()
    {
        txtQuestion.setText(currentQ.getQUESTION());
        ansA.setText(currentQ.getOPTA());
        ansB.setText(currentQ.getOPTB());
        ansC.setText(currentQ.getOPTC());
        qid++;

        showLives();
        showScore();

        TextViewTime=(TextView)findViewById(R.id.TextViewTime);
        TextViewTime.setText("00:10");      

        final CounterClass timer = new CounterClass(10000, 1000);
        timer.start();

    }       


    private void showLives()
    {
        TextView c=(TextView)findViewById(R.id.lives);
        c.setText(String.valueOf(lives));
    }

    private void showScore()
    {
        TextView d=(TextView)findViewById(R.id.score);
        d.setText(String.valueOf(score));
    }

    private void gameOver() {    
        Intent intent = new Intent(QuizActivity.this, ResultActivity.class);  

        Bundle b = new Bundle();                    
        b.putInt("score", score);       
        intent.putExtras(b); 

        Bundle c = new Bundle(); 
        intent.putExtras(c);        

        startActivity(intent);
        finish();
    }

    private void correctAnswer() {


        score+=10;
        Log.d("score", "Your score"+score); // log gia to score

        mpCorrect.start();  

        checkGame();


    }

    private void wrongAnswer() {


        --lives;
        Log.d("lives", "Your lives"+lives);  
        score-=2;
        Log.d("score", "Your score"+score); 
        if (score<0)  
            score=0;        

        mpWrong.start();    

        checkGame();        

    }

    private void checkGame(){
        if(qid<MAX_Q && lives>0){                       
            currentQ=quesList.get(qid);     
            setQuestionView();
        }
        else
            gameOver();
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

您的QuizaActivity不需要实现OnClickListener+OnClick,因为您的自定义OnClickListener已经实现了这一部分

对于你的实际问题:

首先,在类范围内声明反类变量

目前,每次调用setQuestionView时,您都会创建一个名为timer的新变量,并在每次方法完成时销毁引用而不是对象本身,因为它是一个自动变量,只在创建它的方法时才有效

其次,使用现在可用的计时器参考,重置计时器

在自定义OnClick Listener的OnClick中,在检查答案之前,使用timer.cancel;停止计时器

在你的setQuestionView中,最后不仅启动计时器,还创建一个新的计时器,这样你就有了一个满10秒的新计时器,如果旧计时器没有被cancel破坏,它可能会被GC'd;我这里没有IDE,所以无法进行代码爬网

您的新setQuestionView:

private void setQuestionView()
{
    txtQuestion.setText(currentQ.getQUESTION());
    ansA.setText(currentQ.getOPTA());
    ansB.setText(currentQ.getOPTB());
    ansC.setText(currentQ.getOPTC());
    qid++;

    showLives();
    showScore();

    TextViewTime=(TextView)findViewById(R.id.TextViewTime);
    TextViewTime.setText("00:10");      

    timer = new CounterClass(10000, 1000);
    timer.start();

}       

下面是一个示例,可以帮助您了解“取消”是如何工作的

public class TestTimer extends Activity
{

   private final int START_TIME = 10000;
   TextView TextViewTime;
   CounterClass timer = null;
   long millis = START_TIME;

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_quiz);

      TextViewTime = (TextView) findViewById(R.id.textViewTime);

      setTime();

      Button buttonStart = (Button) findViewById(R.id.buttonStart);
      Button buttonStop = (Button) findViewById(R.id.buttonStop);
      Button buttonReset = (Button) findViewById(R.id.buttonReset);

      buttonStart.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View v)
         {
            timer = new CounterClass(millis, 1000);
            timer.start();

         }
      });

      buttonStop.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View v) {
            timer.cancel();
         }
      });

      buttonReset.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View v) {

            millis = START_TIME;
            setTime();
         }
      });
   }



   public class CounterClass extends CountDownTimer {

      public CounterClass(long millisInFuture, long countDownInterval) {
         super(millisInFuture, countDownInterval);
      }

      @Override
      public void onTick(long millisUntilFinished) {
         millis = millisUntilFinished;
         setTime();
      }

      @Override
      public void onFinish() {
         setTime();
      }

   }

   public void setTime() {
      String secs = String.format("00:%02d", TimeUnit.MILLISECONDS.toSeconds(millis));
      TextViewTime.setText(secs);
   }
}
以及琐碎的布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textViewTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start" />
    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="stop" />
    <Button
        android:id="@+id/buttonReset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="reset" />

</LinearLayout>