我有一个带有本地 html、css 和 javascript 文件的 android 应用程序。
其中一个页面包含图像列表,这些图像具有指向附加到它们的外部网站的链接。
每当我单击链接时,URL 都会在 webview 中打开。但是当我点击后退按钮时,它并没有回到上一页。
它适用于所有页面,除了使用外部链接的页面。
MainActivity.java 看起来像这样:
public class MainActivity extends Activity {
WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.loadUrl("file:///android_asset/www/index.html");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
// Force links and redirects to open in the WebView instead of in a browser
}
@Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.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);
}
}
MyAppWebViewClient.java 看起来像这样:
public class MyAppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("/menu")) {
return true;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}