我已經寫了一個倒數計時器的程序,但倒計時開始時只有按鈕點擊,但我希望它沒有按鈕點擊開始,任何人都可以建議我如何做到這一點沒有按鈕點擊?如何在沒有執行任何操作的情況下啓動活動啓動的倒數計時器?
這裏是倒數計時器代碼
public class MainActivity extends ActionBarActivity {
CountDownTimer countDownTimer;
boolean timehasstarted = false;
Button btnStart;
TextView timer;
long startTime = 30 * 1000;
long interval = 1 * 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.button1);
timer = (TextView) findViewById(R.id.timer);
timer.setText(timer.getText() + String.valueOf(startTime/1000));
btnStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!timehasstarted) {
countDownTimer.start();
timehasstarted = true;
timer.setText("Stop");
} else {
countDownTimer.cancel();
timehasstarted = false;
timer.setText("Restart");
}
}
});
countDownTimer = new CountDownTimer(startTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
timer.setText("" + millisUntilFinished/1000);
}
@Override
public void onFinish() {
timer.setText("Time's Up!");
}
};
}
爲什麼你不能啓動的onCreate您的定時器() – 2015-03-19 06:25:24
你怎麼建議我做先生? – 2015-03-19 06:29:29