android studio秒表代码
时间: 2023-05-11 08:03:19 浏览: 108
android 秒表代码
5星 · 资源好评率100%
以下是一个简单的 Android Studio 秒表代码:
```
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Button mStartButton;
private Button mStopButton;
private Button mResetButton;
private Handler mHandler = new Handler();
private long mStartTime;
private long mElapsedTime;
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
mElapsedTime = System.currentTimeMillis() - mStartTime;
int seconds = (int) (mElapsedTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (mElapsedTime % 1000);
mTextView.setText(String.format("%d:%02d:%03d", minutes, seconds, milliseconds));
mHandler.postDelayed(this, 10);
}
};
@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 v) {
mStartTime = System.currentTimeMillis();
mHandler.postDelayed(mRunnable, 0);
}
});
mStopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.removeCallbacks(mRunnable);
}
});
mResetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.removeCallbacks(mRunnable);
mTextView.setText("0:00:000");
}
});
}
}
```
这个代码实现了一个简单的秒表功能,包括开始、停止和重置按钮。当用户点击开始按钮时,秒表开始计时,当用户点击停止按钮时,秒表停止计时,当用户点击重置按钮时,秒表归零。
阅读全文