回答を投稿しようとしたとき、誰かがすでに何らかの解決策を持っていることがわかりました....
しかし、これが私のもので、シンプルで魅力的です。フラグは 1 つだけです ;)
このコードは、ショートプレスとロングプレスを検出します。ロングプレスが発生すると、ショートプレスは起動されません!
注:通常の音量の上下動作が必要な場合は、次のように onKeyPress メソッドで 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);
}