Android随笔之——按键长按事件onKeyLongPress

  现在安卓手机实体键是越来越少了,但还是有的,恰好自己就碰上了:按键的长按事件...百度了一些博客,内容都基本上是完全一样的,虽然可以捕获到长按事件,但却会和正常的单击冲突。幸好最近开个VPN,google,耶~正确答案马上呈现在眼前,特此记录,以防不时之需。

  这里我就直接贴谷歌的代码的,很容易懂,不解释,原文

 1 private boolean shortPress = false;
 2 
 3 @Override
 4 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
 5     if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
 6         shortPress = false;
 7         Toast.makeText(this, "longPress", Toast.LENGTH_LONG).show();
 8         return true;
 9     }
10     //Just return false because the super call does always the same (returning false)
11     return false;
12 }
13 
14 @Override
15 public boolean onKeyDown(int keyCode, KeyEvent event) {
16     if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
17         if(event.getAction() == KeyEvent.ACTION_DOWN){
18             event.startTracking();
19             if(event.getRepeatCount() == 0){
20                 shortPress = true;
21             }
22             return true;
23         }
24     }
25     return super.onKeyDown(keyCode, event);
26 }
27 
28 @Override
29 public boolean onKeyUp(int keyCode, KeyEvent event) {
30     if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
31         if(shortPress){
32             Toast.makeText(this, "shortPress", Toast.LENGTH_LONG).show();
33         } else {
34             //Don't handle longpress here, because the user will have to get his finger back up first
35         }
36         shortPress = false;
37         return true;
38     }
39     return super.onKeyUp(keyCode, event);
40 }

 

posted @ 2014-11-03 13:37  登天路  阅读(20399)  评论(1编辑  收藏  举报