开发环境:
Android Studio,cordova版本5.3.3
问题描述:
经过代码测试发现,menubutton事件绑定后点击无效果
问题分析:
不知道出于什么原因,代码里面并未添加menubutton的注册代码
问题解决:
从按钮点击事件来看, volumedownbutton,volumeupbutton,backbutton,menubutton事件都是一样的,但是CoreAndroid实现上把返回键与音量加减键区分开,注册方法分别为overrideBackbutton和overridebutton方法。接下来我简单地把menubutton用音量加减的方式进行修改。
修改1:CoreAndroid.java
public void overrideButton(String button, boolean override) {
LOG.i("App", "WARNING: Volume Button Default Behavior will be overridden. The volume event will be fired!");
if (button.equals("volumeup")) {
webView.setButtonPlumbedToJs(KeyEvent.KEYCODE_VOLUME_UP, override);
}
else if (button.equals("volumedown")) {
webView.setButtonPlumbedToJs(KeyEvent.KEYCODE_VOLUME_DOWN, override);
}
else if (button.equals("menu")) {
webView.setButtonPlumbedToJs(KeyEvent.KEYCODE_MENU, override);
}
}
修改2:CordovaWebViewImpl.java
@Override
public void setButtonPlumbedToJs(int keyCode, boolean override) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MENU:
// TODO: Why are search and menu buttons handled separately?
if (override) {
boundKeyCodes.add(keyCode);
} else {
boundKeyCodes.remove(keyCode);
}
return;
default:
throw new IllegalArgumentException("Unsupported keycode: " + keyCode);
}
}
修改3:cordova.js
// Add hardware MENU and SEARCH button handlers
//cordova.addDocumentEventHandler('menubutton');
cordova.addDocumentEventHandler('searchbutton');
function bindButtonChannel(buttonName) {
// generic button bind used for volumeup/volumedown buttons
var volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button');
volumeButtonChannel.onHasSubscribersChange = function() {
exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]);
};
}
// Inject a listener for the volume buttons on the document.
bindButtonChannel('volumeup');
bindButtonChannel('volumedown');
bindButtonChannel('menu');
使用方法同volumeup和volumedown一致:
document.addEventListener('deviceready', function(){
document.addEventListener('menubutton',menuKeyDown,false);
},false);
function menuKeyDown(){
alert('menuKeyDown');
}
写完,休息了