用android studio编写一个计时器
时间: 2023-12-04 15:40:56 浏览: 112
以下是一个简单的Android Studio计时器的示例代码:
```java
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Button mButtonStart;
private Button mButtonStop;
private Switch mSwitch; private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = 600000; // 10分钟
private long mEndTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view_countdown);
mButtonStart = findViewById(R.id.button_start);
mButtonStop = findViewById(R.id.button_stop); mSwitch = findViewById(R.id.switch_timer);
mButtonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTimer();
}
});
mButtonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopTimer();
}
});
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mTimeLeftInMillis = 300000; // 5分钟
} else {
mTimeLeftInMillis = 600000; // 10分钟
}
updateCountDownText();
}
});
updateCountDownText();
}
private void startTimer() {
mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
mTimerRunning = false;
mButtonStart.setVisibility(View.VISIBLE);
mButtonStop.setVisibility(View.INVISIBLE);
}
}.start();
mTimerRunning = true;
mButtonStart.setVisibility(View.INVISIBLE);
mButtonStop.setVisibility(View.VISIBLE);
}
private void stopTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
mButtonStart.setVisibility(View.VISIBLE);
mButtonStop.setVisibility(View.INVISIBLE);
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextView.setText(timeLeftFormatted);
}
}
```
这个计时器包括一个文本视图,两个按钮和一个开关。用户可以选择计时器的时间长度,然后按下“开始”按钮启动计时器。计时器将在指定的时间内倒计时,并在计时结束时停止。用户还可以按下“停止”按钮手动停止计时器。
阅读全文