当我准备发布我的答案时,我发现有人已经找到了某种解决方案...
但这里是我的解决方案,简单而且非常有效。只需一个标志 ;)
此代码检测短按和长按,当发生长按时,不会触发短按!
注意:如果您想要正常的音量上下行为,请将onKeyPress方法中的return true更改为super调用,如下所示:
event.startTracking();
if(event.getRepeatCount() == 0){
shortPress = true;
}
return super.onKeyDown(keyCode, event);
没有使用super调用的代码:
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;
}
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 {
}
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;
}
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 {
}
shortPress = false;
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
if(shortPress){
Toast.makeText(this, "shortPress Volume up", Toast.LENGTH_LONG).show();
} else {
}
shortPress = false;
return true;
}
return super.onKeyUp(keyCode, event);
}