1 /* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.launcher3; 18 19 import android.view.View; 20 21 import com.android.launcher3.util.Thunk; 22 23 public class CheckLongPressHelper { 24 25 public static final int DEFAULT_LONG_PRESS_TIMEOUT = 300; 26 27 @Thunk View mView; 28 @Thunk View.OnLongClickListener mListener; 29 @Thunk boolean mHasPerformedLongPress; 30 private int mLongPressTimeout = DEFAULT_LONG_PRESS_TIMEOUT; 31 private CheckForLongPress mPendingCheckForLongPress; 32 33 class CheckForLongPress implements Runnable { 34 public void run() { 35 if ((mView.getParent() != null) && mView.hasWindowFocus() 36 && !mHasPerformedLongPress) { 37 boolean handled; 38 if (mListener != null) { 39 handled = mListener.onLongClick(mView); 40 } else { 41 handled = mView.performLongClick(); 42 } 43 if (handled) { 44 mView.setPressed(false); 45 mHasPerformedLongPress = true; 46 } 47 } 48 } 49 } 50 51 public CheckLongPressHelper(View v) { 52 mView = v; 53 } 54 55 public CheckLongPressHelper(View v, View.OnLongClickListener listener) { 56 mView = v; 57 mListener = listener; 58 } 59 60 /** 61 * Overrides the default long press timeout. 62 */ 63 public void setLongPressTimeout(int longPressTimeout) { 64 mLongPressTimeout = longPressTimeout; 65 } 66 67 public void postCheckForLongPress() { 68 mHasPerformedLongPress = false; 69 70 if (mPendingCheckForLongPress == null) { 71 mPendingCheckForLongPress = new CheckForLongPress(); 72 } 73 mView.postDelayed(mPendingCheckForLongPress, mLongPressTimeout); 74 } 75 76 public void cancelLongPress() { 77 mHasPerformedLongPress = false; 78 if (mPendingCheckForLongPress != null) { 79 mView.removeCallbacks(mPendingCheckForLongPress); 80 mPendingCheckForLongPress = null; 81 } 82 } 83 84 public boolean hasPerformedLongPress() { 85 return mHasPerformedLongPress; 86 } 87 } 88