2014-03-01 207 views
0

我遇到了阻止CountDownTimer的問題。我搜查了很多,但無法理解如何做到這一點。如何停止倒數計時器.....?

以下是我的MainActivity。如何按RadioButtonb?如何停止計時器?

import java.util.Timer; 
import java.util.TimerTask; 

import android.os.Bundle; 
import android.os.CountDownTimer; 
import android.app.Activity; 
import android.content.Intent; 
import android.view.Menu; 
import android.view.View; 
import android.widget.RadioButton; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

    TextView mTextField; 
    RadioButton a, b, c, d, e; 
    final static long interval = 1000; 
    long timeout = 15000; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mTextField = (TextView) findViewById(R.id.tv); 
     a = (RadioButton) findViewById(R.id.rB1a); 
     b = (RadioButton) findViewById(R.id.rB2a); 
     c = (RadioButton) findViewById(R.id.rB3a); 
     d = (RadioButton) findViewById(R.id.rB4a); 
     e = (RadioButton) findViewById(R.id.rB5a); 

     //Timer timer = new Timer(); 
     //timer.scheduleAtFixedRate(task, interval, interval); 

     TimerTask task = new TimerTask() { 
      @Override 
      public void run() { 

       timeout = timeout - interval; 

       if (timeout == 0) { 
        this.cancel(); 
        displayText("finished"); 
        return; 
       } 

       if (timeout >= 0) { 
        displayText("time remaining: " + String.valueOf(timeout/1000)); 
        a.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View arg0) { 
          Toast.makeText(getApplicationContext(), "Wrong Answer!!! ", Toast.LENGTH_LONG).show(); 
          Intent openWordlist = new Intent("com.example.the_vocab_master.AA"); 
          startActivity(openWordlist); 
         } 
        }); 

        b.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View arg0) { 
          Toast.makeText(getApplicationContext(), "GREAT...!!! ", Toast.LENGTH_LONG).show(); 
         } 
        }); 
       } 

       //displayText("time remaining: " + String.valueOf(timeout/1000)); 
      } 
     }; 

     Timer timer = new Timer(); 
     timer.scheduleAtFixedRate(task, interval, interval); 
    } 

    private void displayText(final String text) { 
     this.runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       mTextField.setText(text); 
      } 
     }); 
    } 
} 

回答

0

要取消您的onClick監聽器計時器使用

timer.cancel(); 

。在您的代碼中很難看到,因爲縮進非常糟糕,但我認爲您需要在類中聲明您的變量,而不是在onCreate()中聲明該變量。

此外,我建議你採取兩個setOnClickListener呼籲定時器run()方法外。你在做什麼沒有意義。