现在安卓手机实体键是越来越少了,但还是有的,恰好自己就碰上了:按键的长按事件...百度了一些博客,内容都基本上是完全一样的,虽然可以捕获到长按事件,但却会和正常的单击冲突。幸好最近开个VPN,google,耶~正确答案马上呈现在眼前,特此记录,以防不时之需。
这里我就直接贴谷歌的代码的,很容易懂,不解释,原文
private boolean shortPress = false; @Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
shortPress = false;
Toast.makeText(this, "longPress", Toast.LENGTH_LONG).show();
return true;
}
//Just return false because the super call does always the same (returning false)
return false;
} @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
event.startTracking();
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_VOLUME_DOWN) {
if(shortPress){
Toast.makeText(this, "shortPress", Toast.LENGTH_LONG).show();
} else {
//Don't handle longpress here, because the user will have to get his finger back up first
}
shortPress = false;
return true;
}
return super.onKeyUp(keyCode, event);
}