正如标题所说,CordovaWebView
和android中的onBackPressed
组合在一起会产生奇怪的结果。
我有混合应用程序。我的主要活动有DrawerLayout
和CordovaWebView
。
我的onBackPressed:
@Override
public void onBackPressed(){
if(drawerIsOpen){
//close drawer
}else if(webviewIsIn){
//hide webview
}else{
super.onBackPressed();
}
}
当我使用android的WebView
时,将按预期调用重写的方法。当我更改为CordovaWebView
时,该方法甚至不会被调用,而是调用本地onBackPressed
。
我试过覆盖onKeyDown
和onKeyUp
,但它给了我相同的结果,方法没有被调用。
我使用的是Cordova 2.9.0,测试设备是Galaxy Note 2,Android jellybean 4.2.2
DrawerLayout
具有关闭后退功能,我刚刚禁用它。
我希望你们能理解这个问题。
答案 0 :(得分:2)
我遇到了同样的问题。我的解决方案是从CordovaWebView
派生并使用类似的东西覆盖public boolean onKeyUp(int keyCode, KeyEvent event)
(对于Cordova 3.4.0,代码是CordovaWebView.onKeyUp(int, KeyEvent)
的一部分):
public class CustomCordovaWebView extends CordovaWebView {
protected View mCustomView;
protected boolean bound;
public CustomCordovaWebView(final Context context) {
super(context);
}
public CustomCordovaWebView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public CustomCordovaWebView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
@TargetApi(11)
public CustomCordovaWebView(final Context context, final AttributeSet attrs, final int defStyle, final boolean privateBrowsing) {
super(context, attrs, defStyle, privateBrowsing);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// If back key
if (keyCode == KeyEvent.KEYCODE_BACK) {
// A custom view is currently displayed (e.g. playing a video)
if (mCustomView!=null){
this.hideCustomView();
}else{
// The webview is currently displayed
// If back key is bound, then send event to JavaScript
if (this.bound) {
this.loadUrl("javascript:cordova.fireDocumentEvent('backbutton');");
return true;
} else {
// If not bound
// Go to previous page in webview if it is possible to go back
if (this.backHistory()) {
return true;
}
// If not, then invoke default behavior
else {
//this.activityState = ACTIVITY_EXITING;
//return false;
// If they hit back button when app is initializing, app should exit instead of hang until initialization (CB2-458)
// this.cordova.getActivity().finish();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this thing is closing your activity in CordovaWebView
}
}
}
} else {
return super.onKeyUp(keyCode, event);
}
return false;
}
@Override
public void hideCustomView() {
mCustomView = null;
super.hideCustomView();
}
@Override
public void showCustomView(final View view, final WebChromeClient.CustomViewCallback callback) {
mCustomView = view;
super.showCustomView(view, callback);
}
@Override
public void bindButton(final boolean override) {
bound = override;
super.bindButton(override);
}
}
如果有更好的解决方案,我会对此感兴趣。