android studio实现计时器代码
时间: 2023-10-14 07:27:17 浏览: 98
以下是一个简单的计时器实现代码:
```java
public class MainActivity extends AppCompatActivity {
private TextView mTimerTextView;
private Button mStartButton;
private Button mStopButton;
private Button mResetButton;
private CountDownTimer mCountDownTimer;
private long mTimeLeftInMillis;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimerTextView = findViewById(R.id.timer_text);
mStartButton = findViewById(R.id.start_button);
mStopButton = findViewById(R.id.stop_button);
mResetButton = findViewById(R.id.reset_button);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTimer();
}
});
mStopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopTimer();
}
});
mResetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetTimer();
}
});
}
private void startTimer() {
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateTimer();
}
@Override
public void onFinish() {
mStartButton.setEnabled(true);
mStopButton.setEnabled(false);
}
}.start();
mStartButton.setEnabled(false);
mStopButton.setEnabled(true);
}
private void stopTimer() {
mCountDownTimer.cancel();
mStartButton.setEnabled(true);
mStopButton.setEnabled(false);
}
private void resetTimer() {
mTimeLeftInMillis = 60000; // 初始值为60秒
updateTimer();
mStartButton.setEnabled(true);
mStopButton.setEnabled(false);
}
private void updateTimer() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTimerTextView.setText(timeLeftFormatted);
}
}
```
在布局文件中添加以下代码:
```xml
<TextView
android:id="@+id/timer_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:textSize="48sp"
android:layout_gravity="center_horizontal"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:layout_marginTop="48dp">
<Button
android:id="@+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"/>
<Button
android:id="@+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:enabled="false"
android:layout_marginLeft="24dp"/>
<Button
android:id="@+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:layout_marginLeft="24dp"/>
</LinearLayout>
```
这样就完成了一个简单的计时器的实现。
阅读全文