android 区分按键长按及短按

**

android 区分按键长按及短按

**

正常长按时会一直走onkeydown的,所以区分时最好还是用onkeyup来区分;
注意 event.startTracking(); //只有执行了这行代码才会调用onKeyLongPress的;

 private boolean shortPress = false;

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_3) {
            shortPress = false;
            //长按要执行的代码
            Log.e("onKeyLongPress", "onKeyLongPress");

            return true;
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_3) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                event.startTracking(); //只有执行了这行代码才会调用onKeyLongPress的;
                if (event.getRepeatCount() == 0) {
                    shortPress = true;
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_3) {
            if (shortPress) {
                //短按要执行的代码

                Log.e("onKeyUp", "onKeyUp");

            }
            shortPress = false;
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

你可能感兴趣的:(按键区分长短按)