android studio秒表代码,包含开始、暂停
时间: 2023-05-12 10:03:16 浏览: 184
和重置功能的完整代码是什么?
以下是一个简单的 Android Studio 秒表代码,包含开始、暂停和重置功能的完整代码:
```
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Button mStartButton, mPauseButton, mResetButton;
private Handler mHandler = new Handler();
private long mStartTime, mTimeInMillis, mTimeSwapBuff, mUpdateTime = 0L;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.textView);
mStartButton = findViewById(R.id.startButton);
mPauseButton = findViewById(R.id.pauseButton);
mResetButton = findViewById(R.id.resetButton);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mStartTime = SystemClock.uptimeMillis();
mHandler.postDelayed(mUpdateTimeTask, 0);
}
});
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mTimeSwapBuff += mTimeInMillis;
mHandler.removeCallbacks(mUpdateTimeTask);
}
});
mResetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mTimeInMillis = 0L;
mTimeSwapBuff = 0L;
mUpdateTime = 0L;
mTextView.setText("00:00:00");
}
});
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
mTimeInMillis = SystemClock.uptimeMillis() - mStartTime;
mUpdateTime = mTimeSwapBuff + mTimeInMillis;
int seconds = (int) (mUpdateTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (mUpdateTime % 1000);
mTextView.setText("" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds) + ":" + String.format("%03d", milliseconds));
mHandler.postDelayed(this, 0);
}
};
}
```
这段代码使用了一个 Handler 对象来更新秒表的时间,同时使用了 SystemClock.uptimeMillis() 方法来获取当前时间。开始按钮会记录开始时间并启动一个更新任务,暂停按钮会记录当前时间并停止更新任务,重置按钮会将所有时间重置为零并清空文本视图。
阅读全文