1/*
2 * Copyright (C) 2008 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
17package com.android.internal.widget;
18
19import android.content.Context;
20import android.util.AttributeSet;
21import android.view.KeyEvent;
22import android.view.MotionEvent;
23import android.widget.ImageButton;
24
25import com.android.internal.R;
26
27/**
28 * This class exists purely to cancel long click events.
29 */
30public class NumberPickerButton extends ImageButton {
31
32    private NumberPicker mNumberPicker;
33
34    public NumberPickerButton(Context context, AttributeSet attrs,
35            int defStyle) {
36        super(context, attrs, defStyle);
37    }
38
39    public NumberPickerButton(Context context, AttributeSet attrs) {
40        super(context, attrs);
41    }
42
43    public NumberPickerButton(Context context) {
44        super(context);
45    }
46
47    public void setNumberPicker(NumberPicker picker) {
48        mNumberPicker = picker;
49    }
50
51    @Override
52    public boolean onTouchEvent(MotionEvent event) {
53        cancelLongpressIfRequired(event);
54        return super.onTouchEvent(event);
55    }
56
57    @Override
58    public boolean onTrackballEvent(MotionEvent event) {
59        cancelLongpressIfRequired(event);
60        return super.onTrackballEvent(event);
61    }
62
63    @Override
64    public boolean onKeyUp(int keyCode, KeyEvent event) {
65        if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
66                || (keyCode == KeyEvent.KEYCODE_ENTER)) {
67            cancelLongpress();
68        }
69        return super.onKeyUp(keyCode, event);
70    }
71
72    private void cancelLongpressIfRequired(MotionEvent event) {
73        if ((event.getAction() == MotionEvent.ACTION_CANCEL)
74                || (event.getAction() == MotionEvent.ACTION_UP)) {
75            cancelLongpress();
76        }
77    }
78
79    private void cancelLongpress() {
80        if (R.id.increment == getId()) {
81            mNumberPicker.cancelIncrement();
82        } else if (R.id.decrement == getId()) {
83            mNumberPicker.cancelDecrement();
84        }
85    }
86}
87