Skip to content

Instantly share code, notes, and snippets.

@riyase
Last active December 27, 2016 07:39
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 riyase/05965e2e237657ff7181f32ba9ffc6c4 to your computer and use it in GitHub Desktop.
Save riyase/05965e2e237657ff7181f32ba9ffc6c4 to your computer and use it in GitHub Desktop.
Android custom LongClickListener
Usage
view.setOnTouchListener(new LongClick(new LongClick.Listener() {
@Override
public void onLongClick() {
Log.d(TAG, "onLongClick");
}
@Override
public void onClick() {
Log.d(TAG, "onClick");
}
}, 3000L, 300L));
/**
* Created by riyase on 21/12/16.
*/
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class LongClick implements OnTouchListener{
public interface Listener {
void onLongClick();
void onClick();
}
//private static final long INTERVEL_LONGPRESS=600;
//private long INTERVEL_LONGPRESS_REPEAT=300;
private static final short CLICK_SINGLE=1;
private static final short CLICK_LONG=2;
private short clickType = CLICK_SINGLE;
private static Handler mHandler;
private Listener listener;
private Long time;
private Long timeRepeat;
public LongClick(Listener listener, Long time) {
this.listener = listener;
this.time = time;
}
public LongClick(Listener listener, Long time, Long timeRepeat) {
this.listener = listener;
this.time = time;
this.timeRepeat = timeRepeat;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mHandler == null) {
mHandler = new Handler();
mHandler.postDelayed(mAction, time);
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
clickType = CLICK_SINGLE;
return true;
case MotionEvent.ACTION_CANCEL:
mHandler.removeCallbacks(mAction);
mHandler = null;
return false;
case MotionEvent.ACTION_UP:
if(clickType == CLICK_SINGLE) {
listener.onClick();
}
mHandler.removeCallbacks(mAction);
mHandler = null;
return true;
}
return false;
}
Runnable mAction = new Runnable() {
@Override public void run() {
listener.onLongClick();
clickType = CLICK_LONG;
if (timeRepeat != null) {
mHandler.postDelayed(this, timeRepeat);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment