用户输入和计时器(java android app)

所以我试着制作一个像秒表一样的计时器,但我是一个完整的菜鸟。 我试着“结合”来自这里和这里的东西。

目标是获取用户输入他们想要设置计时器的时间长度,然后当时间到了它就会完成。

这是我到目前为止:

package com.example.timer; import android.app.Activity; import android.os.Bundle; import android.os.CountDownTimer; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private CountDownTimer countDownTimer; private boolean timerHasStarted = false; public TextView text; private final long interval = 1 * 1000; EditText editTime1; Button startButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTime1 = (EditText)findViewById(R.id.editTime1); startButton = (Button)findViewById(R.id.startButton); text = (TextView) this.findViewById(R.id.timer); startButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { //get the name from edittext and storing into string variable long timeVal = Long.parseLong(editTime1.getText().toString()); countDownTimer = new MyCountDownTimer(timeVal, interval); text.setText(text.getText() + String.valueOf(timeVal / 1000)); if (!timerHasStarted) { countDownTimer.start(); timerHasStarted = true; startButton.setText("STOP"); } else { countDownTimer.cancel(); timerHasStarted = false; startButton.setText("RESTART"); } } class MyCountDownTimer extends CountDownTimer { public MyCountDownTimer(long timeVal, long interval) { super(timeVal, interval); } @Override public void onTick(long millisUntilFinished) { text.setText("" + millisUntilFinished / 1000); } @Override public void onFinish() { text.setText("Times up"); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } 

很少有事情需要注意。

  1. Activity期望开始时间以毫秒为单位。 如果给出大于1000的输入值(例如10秒,即10000),则应用程序显示倒计时。

  2. 以下两行放置不正确。

     countDownTimer = new MyCountDownTimer(timeVal, interval); text.setText(text.getText() + String.valueOf(timeVal / 1000)); 

    它们只应在倒计时开始时执行。 但是在给定的实现中,它们既可以在开始也可以在停止时运行。

结果,在倒计时停止时创建一个新的MyCountDownTimer,并且countDownTimer.cancel(); 在这个新对象而不是原始对象中调用。 所以倒数继续。

由于setText在start和stop时都执行,因此timeVal会附加到输出中。 这导致观察到“Times up0”。

更新的onClick方法如下。

  public void onClick(View v) { // get the name from edittext and storing into string variable long timeVal = Long.parseLong(editTime1.getText().toString()); if (!timerHasStarted) { countDownTimer = new MyCountDownTimer(timeVal, interval); text.setText(text.getText() + String.valueOf(timeVal / 1000)); countDownTimer.start(); timerHasStarted = true; startButton.setText("STOP"); } else { countDownTimer.cancel(); timerHasStarted = false; startButton.setText("RESTART"); } }