设计一个Android stopwatch单击“Start”按钮,计时器开始工作,单击“Stop”按钮,计时器停止工作,单击“Reset”按钮,计时器复位。当计时器界面未获得焦点时暂停工作;当计时器重新获得焦点时继续工作。
时间: 2024-02-27 18:57:52 浏览: 201
好的,这是一个比较常见的计时器功能,需要用到Android的计时器类和按钮控件等。我可以给出一个简单的实现步骤,代码仅供参考。
1. 创建一个布局文件,包含三个按钮和一个文本框用于显示计时器时间。
```xml
<LinearLayout>
<Button android:id="@+id/start"
android:text="Start"/>
<Button android:id="@+id/stop"
android:text="Stop"/>
<Button android:id="@+id/reset"
android:text="Reset"/>
<TextView android:id="@+id/time"/>
</LinearLayout>
```
2. 在Activity中找到这些控件,并为按钮设置点击事件。
```java
public class StopwatchActivity extends Activity implements View.OnClickListener {
private Button startButton;
private Button stopButton;
private Button resetButton;
private TextView timeText;
private Timer timer;
private long startTime;
private long elapsedTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
startButton = (Button) findViewById(R.id.start);
stopButton = (Button) findViewById(R.id.stop);
resetButton = (Button) findViewById(R.id.reset);
timeText = (TextView) findViewById(R.id.time);
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
startTimer();
break;
case R.id.stop:
stopTimer();
break;
case R.id.reset:
resetTimer();
break;
}
}
private void startTimer() {
startTime = System.currentTimeMillis() - elapsedTime;
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
final long millis = System.currentTimeMillis() - startTime;
runOnUiThread(new Runnable() {
@Override
public void run() {
updateTime(millis);
}
});
}
}, 0, 1000);
}
private void stopTimer() {
if (timer != null) {
timer.cancel();
timer = null;
elapsedTime = System.currentTimeMillis() - startTime;
}
}
private void resetTimer() {
stopTimer();
elapsedTime = 0;
updateTime(elapsedTime);
}
private void updateTime(long millis) {
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timeText.setText(String.format("%d:%02d", minutes, seconds));
}
}
```
3. 在Activity中实现焦点变化的监听器,当计时器界面失去焦点时暂停计时器,重新获得焦点时继续计时。
```java
public class StopwatchActivity extends Activity implements View.OnClickListener {
// 省略其他代码
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
startTimer();
} else {
stopTimer();
}
}
}
```
这样就可以实现一个简单的Android计时器了。注意,代码仅供参考,具体实现可能需要根据实际需求进行一些修改和优化。
阅读全文
相关推荐

















