1/*
2 * Copyright (c) 2016, 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 */
16package com.android.car.hvac.ui;
17
18import android.os.Handler;
19import android.view.MotionEvent;
20import android.view.View;
21import android.view.View.OnClickListener;
22import android.view.View.OnTouchListener;
23
24/**
25 * A wrapper for a click listener that repeats the click when a press and hold action takes place.
26 */
27public class PressAndHoldTouchListener implements OnTouchListener {
28    private static final int REPEAT_ACTION_DELAY_MS = 100;
29    private static final int FIRST_ACTION_DELAY_MS = 300;
30
31    private Handler mHandler = new Handler();
32
33    private final OnClickListener clickListener;
34
35    private View mView;
36
37    public PressAndHoldTouchListener(OnClickListener clickListener) {
38        this.clickListener = clickListener;
39    }
40
41    public boolean onTouch(View view, MotionEvent motionEvent) {
42        switch (motionEvent.getAction()) {
43            case MotionEvent.ACTION_DOWN:
44                mHandler.removeCallbacks(mRepeatedAction);
45                mHandler.postDelayed(mRepeatedAction, FIRST_ACTION_DELAY_MS);
46                mView = view;
47                mView.setPressed(true);
48                clickListener.onClick(view);
49                return true;
50            case MotionEvent.ACTION_CANCEL:
51            case MotionEvent.ACTION_UP:
52                mHandler.removeCallbacks(mRepeatedAction);
53                mView.setPressed(false);
54                mView = null;
55                return true;
56            default:
57                return false;
58        }
59    }
60
61    private Runnable mRepeatedAction = new Runnable() {
62        @Override
63        public void run() {
64            mHandler.postDelayed(this, REPEAT_ACTION_DELAY_MS);
65            clickListener.onClick(mView);  //
66        }
67    };
68}