There is a timer (registered in OnCreate):

CountDownTimer timer; timer = new CountDownTimer(10000, 1000) { public void onTick(long millisUntilFinished) { text_d1.setText("Осталось: "+ millisUntilFinished / 1000); public void onFinish() { text_d1.setText("Время вышло"); } }.start(); 

There is a keystroke processing method on the virtual keyboard:

  public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && (keyCode == KeyEvent.KEYCODE_ENTER)) { // тут разные условия, в зависимости от того, в каком edittext нажата клавиша ввод return true; } return false; } 

The logic is as follows:

As soon as the activation is opened, the timer starts.

The timer automatically stops after 10 seconds.

How to add a condition that the timer also stops if the key on the keyboard is pressed?

  • 2
    timer.cancel() in the enter key processing method - pavlofff
  • Yes, I tried it, but as YuriySPb correctly noted, the variable had to be declared at the class level. But anyway, thanks for the reply) - VolhaGomel

1 answer 1

Most likely you just need to call timer.cancel() in the right place. But for this you need to have access to the variable timer . And access to it in different handlers can be obtained if it is declared not inside the onCreate method, but at the onCreate level. Ie, approximately, like this:

 CountDownTimer timer; public void onCreate(Bundle b) { ... } 
  • Thank you, Yuri, helped. I still have little experience (only less than a month), and in fact I felt that the fact was that the variable was declared in onCreate))). The question has changed a little, if it's easy, help with the decision. I did not find a solution on the Internet. - VolhaGomel
  • @VolhaGomel, if my answer solved the original problem, then you should vote for it and mark it true by clicking on the check mark to the left of the answer. When a new question arises, you need to ask a new question, and not to change the current one. - Yuriy SPb
  • @VolhaGomel, asking a new question, you can roll back the changes in this by clicking on the link for the question changed 6 min. back and clicking откат on the old version. - Yuriy SPb