Last active
August 29, 2015 14:01
-
-
Save ruuhkis/68738ada3c8d3c3ca983 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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