1. 程式人生 > >RecyclerView監聽事件

RecyclerView監聽事件

public class RecyclerViewClickListener implements RecyclerView.OnItemTouchListener {
    private int mLastDownX,mLastDownY;
    //該值記錄了最小滑動距離
    private int touchSlop ;
    private OnItemClickListener mListener;
    //是否是單擊事件
    private boolean isSingleTapUp = false;
    //是否是長按事件
    private boolean isLongPressUp 
= false; private boolean isMove = false; private long mDownTime; //內部介面,定義點選方法以及長按方法 public interface OnItemClickListener { void onItemClick(View view, int position); void onItemLongClick(View view, int position); } public RecyclerViewClickListener(Context context, OnItemClickListener listener){ touchSlop
= ViewConfiguration.get(context).getScaledTouchSlop(); mListener = listener; } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { int x = (int) e.getX(); int y = (int) e.getY(); switch (e.getAction()){ /** *
如果是ACTION_DOWN事件,那麼記錄當前按下的位置, * 記錄當前的系統時間。 */ case MotionEvent.ACTION_DOWN: mLastDownX = x; mLastDownY = y; mDownTime = System.currentTimeMillis(); isMove = false; break; /** * 如果是ACTION_MOVE事件,此時根據TouchSlop判斷使用者在按下的時候是否滑動了, * 如果滑動了,那麼接下來將不處理點選事件 */ case MotionEvent.ACTION_MOVE: if(Math.abs(x - mLastDownX)>touchSlop || Math.abs(y - mLastDownY)>touchSlop){ isMove = true; } break; /** * 如果是ACTION_UP事件,那麼根據isMove標誌位來判斷是否需要處理點選事件; * 根據系統時間的差值來判斷是哪種事件,如果按下事件超過1ms,則認為是長按事件, * 否則是單擊事件。 */ case MotionEvent.ACTION_UP: if(isMove){ break; } if(System.currentTimeMillis()-mDownTime > 1000){ isLongPressUp = true; }else { isSingleTapUp = true; } break; } if(isSingleTapUp ){ //根據觸控座標來獲取childView View childView = rv.findChildViewUnder(e.getX(),e.getY()); isSingleTapUp = false; if(childView != null){ //回撥mListener#onItemClick方法 mListener.onItemClick(childView,rv.getChildLayoutPosition(childView)); return true; } return false; } if (isLongPressUp ){ View childView = rv.findChildViewUnder(e.getX(),e.getY()); isLongPressUp = false; if(childView != null){ mListener.onItemLongClick(childView, rv.getChildLayoutPosition(childView)); return true; } return false; } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }


//點選監聽

mrecyclerview1.addOnItemTouchListener(new RecyclerViewClickListener(getActivity(), new RecyclerViewClickListener.OnItemClickListener() {
    @Override
    public void onItemClick(View view, int position) {
       
    }
    @Override
    public void onItemLongClick(View view, int position) {
    }
}));