2015-10-09 84 views
0

我想爲我的應用程序實現一個倒計時小部件。在編寫代碼時,我需要幫助,使它以一個按鈕開始,並在時間到了時自動停止,然後顯示文本「完成」。任何幫助是極大的讚賞 !先謝謝你 !Android Studio CountDownTimer

我實際上已經嘗試了一些代碼示例。 Gradle能夠成功運行,沒有任何問題。但是,當我點擊開始按鈕時,沒有任何反應。下面是我使用的代碼:

public class countdown extends AppCompatActivity { 

Button buttonStart; 
TextView textCounter; 

MyCountDownTimer myCountDownTimer; 

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

    buttonStart = (Button)findViewById(R.id.start); 
    textCounter = (TextView)findViewById(R.id.counter); 

    buttonStart.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      myCountDownTimer = new MyCountDownTimer(30000, 1000); 
      myCountDownTimer.start(); 
     } 
    }); 

} 
public class MyCountDownTimer extends CountDownTimer { 

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

    @Override 
    public void onTick(long millisUntilFinished) { 
     textCounter.setText("seconds remaining: " + millisUntilFinished/1000); 

    } 

    @Override 
    public void onFinish() { 
     textCounter.setText("Finished!"); 
    } 


}} 

回答

0

將這個代碼在你點擊按鈕聽衆:

new CountDownTimer(30000, 1000) {//CountDownTimer(edittext1.getText()+edittext2.getText()) also parse it to long 

public void onTick(long millisUntilFinished) { 
    mTextField.setText("seconds remaining: " + millisUntilFinished/1000); 
    //here you can have your logic to set text to edittext 
} 

public void onFinish() { 
    mTextField.setText("finished!"); 
} 
} 
.start(); 

請參閱本link

+0

嗨,仍然無法成功地運行應用程序。這是在logcat上發現的錯誤。 java.lang.NullPointerException:嘗試在空對象引用 – Kendrick

+0

上調用虛擬方法'void android.widget.TextView.setText(java.lang.CharSequence)'用文本計數器替換mTextField – Nirel

+0

嘿,它沒有解決問題。它仍然崩潰 – Kendrick