安卓番茄钟app实现代码
时间: 2024-05-11 15:20:10 浏览: 181
以下是一个简单的安卓番茄钟App实现代码,使用了CountDownTimer类来实现倒计时:
```
public class MainActivity extends AppCompatActivity {
private TextView timerTextView;
private Button startButton;
private Button resetButton;
private CountDownTimer countDownTimer;
private long timeLeftInMilliseconds = 1500000; // 25 minutes
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTextView = findViewById(R.id.timerTextView);
startButton = findViewById(R.id.startButton);
resetButton = findViewById(R.id.resetButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startTimer();
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
resetTimer();
}
});
updateTimer();
}
private void startTimer() {
countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
@Override
public void onTick(long l) {
timeLeftInMilliseconds = l;
updateTimer();
}
@Override
public void onFinish() {
resetTimer();
Toast.makeText(MainActivity.this, "Time's up!", Toast.LENGTH_SHORT).show();
}
}.start();
startButton.setEnabled(false);
resetButton.setEnabled(true);
}
private void resetTimer() {
if (countDownTimer != null) {
countDownTimer.cancel();
}
timeLeftInMilliseconds = 1500000;
updateTimer();
startButton.setEnabled(true);
resetButton.setEnabled(false);
}
private void updateTimer() {
int minutes = (int) timeLeftInMilliseconds / 60000;
int seconds = (int) timeLeftInMilliseconds % 60000 / 1000;
String timeLeftText;
if (seconds < 10) {
timeLeftText = minutes + ":0" + seconds;
} else {
timeLeftText = minutes + ":" + seconds;
}
timerTextView.setText(timeLeftText);
}
}
```
需要注意的是,这只是一个简单的实现,实际上番茄钟App还包括了一些其他的功能和设置,比如暂停、调整时间长度、提醒等等。如果你想要开发一个完整的番茄钟App,需要进一步完善代码。
阅读全文