안드로이드 Long Press (Long Click) 직접구현하기 |
안드로이드를 사용하다 보면 가끔 view 끼리의 focus 나 touch event 문제 등에 봉착하여
Long Press ( Long Click ) 을 직접 구현해야 할 때가 있다.
그래서 한번 구현해보았다.
public class LongPressChecker {
public interface OnLongPressListener{
public void onLongPressed();
}
private Handler mHandler = new Handler();
private LongPressCheckRunnable mLongPressCheckRunnable = new LongPressCheckRunnable();
private int mLongPressTimeout;
private int mScaledTouchSlope;
private View mTargetView;
private OnLongPressListener mOnLongPressListener;
private boolean mLongPressed = false;
private float mLastX;
private float mLastY;
public LongPressChecker( Context context ){
if ( Looper.myLooper() != Looper.getMainLooper() )
throw new RuntimeException();
mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
mScaledTouchSlope = ViewConfiguration.get( context ).getScaledTouchSlop();
}
public void setOnLongPressListener( OnLongPressListener listener ){
mOnLongPressListener = listener;
}
public void deliverMotionEvent( View v, MotionEvent event ){
switch( event.getAction() ){
case MotionEvent.ACTION_DOWN:
mTargetView = v;
mLastX = event.getX();
mLastY = event.getY();
startTimeout();
break;
case MotionEvent.ACTION_MOVE:
float x = event.getX();
float y = event.getY();
if ( Math.abs( x - mLastX ) > mScaledTouchSlope || Math.abs( y - mLastY ) > mScaledTouchSlope )
stopTimeout();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
stopTimeout();
break;
}
}
public void startTimeout(){
mLongPressed = false;
mHandler.postDelayed( mLongPressCheckRunnable, mLongPressTimeout );
}
public void stopTimeout(){
if ( !mLongPressed )
mHandler.removeCallbacks( mLongPressCheckRunnable );
}
private class LongPressCheckRunnable implements Runnable{
@Override
public void run() {
mLongPressed = true;
if ( mOnLongPressListener != null ){
mTargetView.performHapticFeedback( HapticFeedbackConstants.LONG_PRESS );
mOnLongPressListener.onLongPressed();
}
}
}
}
'프로그래밍 놀이터 > 안드로이드, Java' 카테고리의 다른 글
[android] Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE (0) | 2013.07.08 |
---|---|
[android] contextmenu 관련 함수들 (0) | 2013.07.07 |
[android] 기본 Longpress 진동주기 (0) | 2013.07.04 |
[android] 현재 thread가 main thread 인지 체크하는 방법. (0) | 2013.07.04 |
윈도우에서 openssl 사용하기. (0) | 2013.07.03 |
댓글