본문 바로가기
프로그래밍 놀이터/안드로이드, Java

[android] Long Press ( Long Click ) 직접 구현하기

by 돼지왕 왕돼지 2013. 7. 7.
반응형


 안드로이드 Long Press (Long Click) 직접구현하기

 


[android] 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();

}

}

}

}


구현은 대충 저렇다.
Long Press 이기 때문에 haptic feedback 까지 해주는 쓸데없는 센스.





사용은..

button.setOnTouchListener( new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mLongPressChecker.deliverMotionEvent( v, event );
return false;
}
});

mLongPressChecker = new LongPressChecker( this );
mLongPressChecker.setOnLongPressListener( new OnLongPressListener() {
@Override
public void onLongPressed() {
openContextMenu( listview );
}
});


저런 식으루 ㅎ






반응형

댓글0