当我正要发布我的答案时,我发现有人已经有了某种解决方案....
但这是我的,简单,就像一个魅力。只有一个标志;)
此代码检测短按和长按,当长按发生时不会触发短按!
注意:如果您想要正常的音量上下行为,请将 onKeyPress 方法中的 return true 更改为 super 调用,如下所示:
event.startTracking();
if(event.getRepeatCount() == 0){
shortPress = true;
}
//return true;
return super.onKeyDown(keyCode, event);
没有超级调用的代码:
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);
}
此处的代码是添加了音量增大键,只需选择您的一边;)
private boolean shortPress = false;
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
shortPress = false;
Toast.makeText(this, "longPress Volume Down", Toast.LENGTH_LONG).show();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
shortPress = false;
Toast.makeText(this, "longPress Volume Up", 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 || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
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 Volume Down", 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;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
if(shortPress){
Toast.makeText(this, "shortPress Volume up", 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);
}