Skip to content

Instantly share code, notes, and snippets.

@ruuhkis
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruuhkis/68738ada3c8d3c3ca983 to your computer and use it in GitHub Desktop.
Save ruuhkis/68738ada3c8d3c3ca983 to your computer and use it in GitHub Desktop.
import android.os.Handler;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.View.OnTouchListener;
public abstract class RepeatTouchListener implements OnTouchListener {
private Handler mHandler;
private int currentDelay;
private static final int INITIAL_DELAY = 500;
private static final int MIN_DELAY = 100;
private static final double APPROACH_PERCENT = 0.25;
private static final int THRESHOLD = 10;
private View view;
public RepeatTouchListener(View view) {
this.view = view;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
view.playSoundEffect(SoundEffectConstants.CLICK);
onRepeat();
if (mHandler != null)
return true;
mHandler = new Handler();
currentDelay = INITIAL_DELAY;
mHandler.postDelayed(mAction, currentDelay);
break;
case MotionEvent.ACTION_UP:
if (mHandler == null)
return true;
mHandler.removeCallbacks(mAction);
mHandler = null;
break;
}
return false;
}
Runnable mAction = new Runnable() {
@Override
public void run() {
view.playSoundEffect(SoundEffectConstants.CLICK);
int minOffset = (currentDelay - MIN_DELAY);
if (minOffset < THRESHOLD) {
currentDelay = MIN_DELAY;
} else {
currentDelay = currentDelay
- (int) (minOffset * APPROACH_PERCENT);
}
onRepeat();
mHandler.postDelayed(this, currentDelay);
}
};
public abstract void onRepeat();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment