问题
I'm developing a Javascript based web app and thought that I could use Android's WebView
ability to make it like an actual app, so I jumped right into Android Studio and made a simple WebView
app without any Java knowledge, but the problem is, between page transitions whenever I want to return back and hit the back button, the app closes itself. I found some solutions but I have no idea how to implement them correctly, so can you help me please? Here are my WebView's FullscreenActivity.java
codes.
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new ZeroBrowser());
view.loadUrl("http://www.google.com");
}
private class ZeroBrowserOverride extends WebViewClient implements ZeroBrowserOverride {
@Override
public boolean ShouldOverrideUrlLoading(WebView view, String Url){
view.loadUrl(Url);
return true;
}
}
Thank you so much!
回答1:
You can try with this .
WebView view ; //Global
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new ZeroBrowser());
view.loadUrl("http://www.google.com");
}
Then
@Override
public void onBackPressed() {
if (view.canGoBack()) {
view.goBack();
} else {
super.onBackPressed();
}
}
How to go back to previous page if back button is pressed in WebView?
http://developer.android.com/intl/es/guide/webapps/webview.html
回答2:
You can check the clients history to go back within webview. Implement something like this:
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
回答3:
In your WebView class (or in parent view) override the listener:
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.canGoBack()) {
this.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
来源:https://stackoverflow.com/questions/33546673/back-button-kicks-me-out-of-the-app-on-webview