用eclipse移动应用开发设计一个计时器,包括main文件和java文件
时间: 2024-04-30 08:22:00 浏览: 81
以下是一个基本的计时器应用程序的main文件和java文件示例,使用Eclipse开发,希望可以帮助您入门移动应用程序开发:
Main文件:
```java
package com.example.timer;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
```
Java文件:
```java
package com.example.timer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private int seconds = 0;
private boolean running;
private boolean wasRunning;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
seconds = savedInstanceState.getInt("seconds");
running = savedInstanceState.getBoolean("running");
wasRunning = savedInstanceState.getBoolean("wasRunning");
}
runTimer();
Button startButton = findViewById(R.id.start_button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
running = true;
}
});
Button stopButton = findViewById(R.id.stop_button);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
running = false;
}
});
Button resetButton = findViewById(R.id.reset_button);
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
running = false;
seconds = 0;
}
});
}
private void runTimer() {
final TextView timeView = findViewById(R.id.time_view);
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int secs = seconds % 60;
String time = String.format("%d:%02d:%02d", hours, minutes, secs);
timeView.setText(time);
if (running) {
seconds++;
}
handler.postDelayed(this, 1000);
}
});
}
@Override
protected void onResume() {
super.onResume();
if (wasRunning) {
running = true;
}
}
@Override
protected void onPause() {
super.onPause();
wasRunning = running;
running = false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("seconds", seconds);
outState.putBoolean("running", running);
outState.putBoolean("wasRunning", wasRunning);
}
}
```
请注意,此示例仅包括计时器应用程序的基本功能,并且还可以进行许多其他改进和自定义,具体取决于您的需求和偏好。
阅读全文