我正在我的应用中加载HTML
中本地存储的WebView
文件的内容。此文件还包含其中的链接,单击此链接后,将URLs
加载到同一WebView
中。我想在外部浏览器中加载这些链接。我查看了onPageStarted
和shouldOverrideUrlLoading
,但它们似乎无法正常工作。我尝试过以下方法:
webAbout = (WebView) findViewById(R.id.wvAbout);
webAbout.loadUrl(Const.defURL);
webAbout.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
if (!url.startsWith(Const.defURL)) {
view.stopLoading();
// DO SOMETHING
}else{
view.loadUrl(Const.defURL);
}
}
});
我也尝试过:
webAbout = (WebView) findViewById(R.id.wvAbout);
webAbout.loadUrl(Const.defURL);
webAbout.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith(Const.defURL))){
webAbout.loadUrl(Const.defURL);
return true;
}
else {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return false;
}
}
});
但在这两种情况下,WebView
都不会加载任何内容。知道我哪里错了吗?
答案 0 :(得分:1)
如果您希望在WebView中加载URL,请从false
返回shouldOverrideUrlLoading
,如果您不希望WebView加载URL,则返回true
(这意味着您已经以某种方式自己处理。)
请记住:
WebViewClient
之前设置loadUrl
,shouldOverrideUrlLoading
未调用传递给loadUrl
的网址。您所拥有的代码应该进行一些修改:
webAbout.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith(Const.defURL))){
return false;
} else {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
}
});
// I'm assuming Const.defURL doesn't need escaping.
String customHtml = "<html><body><a href=\"" + Const.defURL + "\">Load url in webview</a><a href=\"http://stackoverflow.com/\">load in browser</a></body></html>";
// Here you would normally load your page using loadUrl,
webAbout.loadData(customHtml, "text/html", "UTF-8");
答案 1 :(得分:0)
试试这个
webView=(WebView)findViewById(R.id.wvAbout);
String url="";
webView.loadUrl(url);
或写下这个条件
if (urlPath
.compareToIgnoreCase(Const.defURL) == 0) {
} else {
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.clearView();
view.loadUrl(url);
return true;
}
});
}
答案 2 :(得分:0)
将您的第二种方法更改为:
webAbout = (WebView) findViewById(R.id.wvAbout);
webAbout.loadUrl(Const.defURL);
webAbout.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith(Const.defURL))){
view.loadUrl(url); //use new url instead of const.defURL
return true;
} else {
//use browser
return super.shouldOverrideUrlLoading(view, url);
}
}
});