android - 定时按钮点击
问题描述:
我将如何解决button1 onClick和button2 onClick之间的流逝时间。android - 定时按钮点击
这是我写的,但它不工作,只是打印当前时间。
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
private long startTime = System.currentTimeMillis();
}
});
stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final long endTime = System.currentTimeMillis();
final long elapsedTime = endTime - startTime;
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/timer.txt", true));
out.write("Elapsed time:" + dateFormat.format(new Date(elapsedTime)));
out.write("\r\n");
out.close();
} catch (Exception e) {
}
}
});
,因为我很茫然
千恩万谢
答
这应该工作的任何帮助将不胜感激。
private long startTime;
private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
public void OnCreate(Bundle b) {
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startTime = System.currentTimeMillis();
}
});
stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long elaspedTime = System.currentTimeMillis() - startTIme;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/timer.txt", true));
out.write("Elapsed time:" + dateFormat.format(new Date(elapsedTime)));
out.write("\r\n");
out.close();
} catch (Exception e) {
}
}
});
}
+0
多数民众赞成在此非常感谢你 – Leigh8347
答
声明startTime
作为属性。
private long startTime;
在第一onClick(...)
,代码更改为:
startTime = System.currentTimeMillis();
这应该工作。顺便说一句,你不必final
你的变量在第二onClick(...)
。
那么,你的代码甚至不会编译。你不能在开始按钮监听器的onClick方法中声明成员变量:'private long startTime = System.currentTimeMillis();' – user802421
那么我需要做什么?我想你可以告诉,但我很困惑 – Leigh8347