用Android Studio设计StopWatch APP。单击“Start”按钮,计时器开始工作,单击“Stop”按钮,计时器停止工作,单击“Reset”按钮,计时器复位。当计时器界面未获得焦点时暂停工作;当计时器重新获得焦点时继续工作的代码
时间: 2023-05-20 21:04:12 浏览: 238
以下是一个简单的 StopWatch APP 的代码,可以在 Android Studio 中使用:
```
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Button mStartButton, mStopButton, mResetButton;
private Handler mHandler = new Handler();
private long mStartTime, mTimeInMillis;
private boolean mIsRunning;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
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 view) {
startTimer();
}
});
mStopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopTimer();
}
});
mResetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
resetTimer();
}
});
}
private void startTimer() {
if (!mIsRunning) {
mStartTime = System.currentTimeMillis() - mTimeInMillis;
mHandler.postDelayed(mRunnable, 0);
mIsRunning = true;
}
}
private void stopTimer() {
if (mIsRunning) {
mHandler.removeCallbacks(mRunnable);
mTimeInMillis = System.currentTimeMillis() - mStartTime;
mIsRunning = false;
}
}
private void resetTimer() {
mTimeInMillis = 0;
updateTimerText();
}
private void updateTimerText() {
int minutes = (int) (mTimeInMillis / 1000) / 60;
int seconds = (int) (mTimeInMillis / 1000) % 60;
int milliseconds = (int) (mTimeInMillis % 1000) / 10;
String time = String.format(Locale.getDefault(), "%02d:%02d:%02d", minutes, seconds, milliseconds);
mTextView.setText(time);
}
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
mTimeInMillis = System.currentTimeMillis() - mStartTime;
updateTimerText();
mHandler.postDelayed(this, 10);
}
};
@Override
protected void onPause() {
super.onPause();
if (mIsRunning) {
mHandler.removeCallbacks(mRunnable);
}
}
@Override
protected void onResume() {
super.onResume();
if (mIsRunning) {
mHandler.postDelayed(mRunnable, 0);
}
}
}
```
这个 APP 包含了三个按钮:Start、Stop 和 Reset。当用户单击 Start 按钮时,计时器开始工作;当用户单击 Stop 按钮时,计时器停止工作;当用户单击 Reset 按钮时,计时器复位。当计时器界面未获得焦点时暂停工作,当计时器重新获得焦点时继续工作。
阅读全文