如何在默认浏览器和WebView Android中的所有内部链接中打开外部URL?
我在页面中使用WebView
,并在WebView
中使用本地文件assets
进行显示,但在外部主网站(非本地)的HTML主页中,我想在用户的默认浏览器中仅打开该链接设备
I am using WebView
in my page and using local file assets
to displaying in WebView
but in main HTML page external website (not local) and I want to open just that link in default Browser on the users device
这是我在'onCreate'方法中的代码
This is my code in 'onCreate' method
WebView v;
v=(WebView) rootView.findViewById(R.id.webView1);
v.getSettings().setJavaScriptEnabled(true);
WebViewClient vc= new WebViewClient();
v.setWebViewClient(vc);
v.loadUrl("file:///android_asset/home.html");
当我运行该应用程序时,内部链接可以正常工作,但是外部链接"www.apple.com"在网络视图中可以访问
When I run the application the internal link is working good but the external link "www.apple.com" en in the web view
我搜索了相同的问题并找到了此解决方案,但外部链接仍在WebView中打开
I searched the same question and found this solution but still external link opens in WebView
WebView webView = (WebView) rootView.findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
String url = "file:///android_asset/home.html";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
和班级
class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("http")){ // Could be cleverer and use a regex
return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
} else {
view.loadUrl(url); // Stay within this webview and load url
return true;
}
}
}
更改
if (url.contains("http")) { // Could be cleverer and use a regex
return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
} else {
view.loadUrl(url); // Stay within this webview and load url
return true;
}
到
if (url.contains("http")) { // Could be cleverer and use a regex
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
mContext.startActivity(intent);
return true;
}
return false;
注意:将mContext
替换为您的活动上下文.
Note : replace mContext
with your activity context.