There is a method that draws shapes, conditional name drawImage (). With a single click, it is necessary that this method be executed once, and when pressed and held, it is repeated while the button is held down. With a single click, everything is clear

View.OnClickListener onclBtn = new View.OnClickListener() { @Override public void onClick(View v) { drawImage(); } }; 

How to implement multiple repetitions while holding?

  • you need onTouchListener () and catch touch types ACTION_DOWN & ACTION_UP - Sviat Volkov
  • This is yes, but repeatability is needed, so you need to select a stream and stop it. The question is how to do this? - kaaa

1 answer 1

Try something like this

  final View.OnTouchListener listener = new View.OnTouchListener() { private Handler mHandler; //создаем флаг private boolean downWithoutUp = false; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: //включаем Handler if (mHandler != null) return true; mHandler = new Handler(); switch (v.getId()) { case R.id.image_id: mHandler.postDelayed(runnable, 500);//период удержания после которого сработает Handler в UP (ms) break; } return true; case MotionEvent.ACTION_UP: //отключаем Handler if (mHandler == null) return true; mHandler.removeCallbacks(runnable); mHandler = null; switch (v.getId()) { case R.id.image_id: if (!downWithoutUp) {//если UP не сработал drawImage();//то вызываем наш метод } break; } downWithoutUp = false; return true; } return false; } Runnable runnable = new Runnable() { @Override public void run() { downWithoutUp = true;//устанавливаем флагу true, сработал UP drawImage(); mHandler.postDelayed(this, 250); } }; }; 
  • Fine! Exactly what you need. Truth had to turn off the listener on a single touch. And you can use this and that? - kaaa
  • @kaaa: case MotionEvent.ACTION_UP: will work when you lift your finger, this will be a single tap. Another listener to anything - TimurVI
  • It does not work "click quickly." Skips two, three clicks. - kaaa
  • @kaaa: updated answer, read carefully comments - TimurVI
  • @kaaa: still deleted the extra call to drawImage () in UP - TimurVI