0
我正在實現一個countup定時器,我遵循StackoverFlow的一個例子。 在我的版本中,我將按開始按鈕開始計數,停止按鈕停止。 但問題是,我進入活動後立即開始計數。 任何想法如何使它成爲我想要的方式?只有當按鈕按下時,如何設置一個計數器定時器?
public class StartActivity extends Activity
{
Button beginRecordingButton;
TextView timer;
long startTime;
long countup;
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.startactivity);
beginRecordingButton = (Button) findViewById(R.id.BeginRecording);
timer = (TextView) findViewById(R.id.timer);
final Chronometer stopwatch = (Chronometer) findViewById(R.id.chrono);
startTime = SystemClock.elapsedRealtime();
stopwatch.setOnChronometerTickListener(listener);
beginRecordingButton.setOnClickListener(new OnClickListener()
{
int counter = 0;
public void onClick(View v)
{
if (counter % 2 == 0)
{
stopwatch.start();
beginRecordingButton.setText("Stop");
}
if (counter % 2 == 1)
{
stopwatch.stop();
beginRecordingButton.setText("Begin");
}
counter++; //counter is used for knowing it is stop or begin
}
});
}
private OnChronometerTickListener listener = new OnChronometerTickListener()
{
public void onChronometerTick(Chronometer chronometer)
{
String text;
countup = (SystemClock.elapsedRealtime() - chronometer.getBase())/1000;
if(countup%60<10)
{
text = (countup/60) + ":0" + (countup%60);
}
else
{
text = (countup/60) + ":" + (countup%60);
}
timer.setText(text);
}
};
}