2012-07-21 63 views
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); 
     } 
    }; 
} 

回答

0

我做后续找到了解决办法:

long test; 

test = (SystemClock.elapsedRealtime() - stopwatch.getBase())/1000; 
Log.i(TAG, = (SystemClock.elapsedRealtime() - chronometer.getBase())/1000 - test; 

basically String.valueOf(test)); 
stopwatch.start(); 

计数进位的想法是,如果我按下启动按钮,它从0

去减去经过时间
相关问题