我正在开展一个项目,我需要检测按下音量降低按钮以及长按该键。我尝试使用onKeyDown方法和onKeyLongPress方法。但它不起作用。我怎么能绕过这个?
答案 0 :(得分:4)
这可以使用标志来完成。您可以设置2个布尔标志,这些标志将根据用户与降低音量键的交互方式进行打开和关闭。
PS - 你可以通过简单地放置按钮随附的KeyEvent id来将密钥更改为Volume up或任何其他密钥。
这是代码 -
import android.view.KeyEvent;
boolean shortPress = false;
boolean longPress = false;
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
Toast.makeText(this, "Long Press", Toast.LENGTH_SHORT).show();
//Long Press code goes here
shortPress = false;
longPress = true;
return true;
}
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
if (longPress == true) {
shortPress = false;
} else {
shortPress = true;
longPress = false;
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
if (shortPress) {
Toast.makeText(this, "Short Press", Toast.LENGTH_SHORT).show();
//Short Press code goes here
}
shortPress = true;
longPress = false;
return true;
}
return super.onKeyUp(keyCode, event);
}