Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.