android - 使用 loadDataWithBaseURL 禁用 webview 中的链接
问题描述
我使用以下代码加载电子书的 html 内容,其中 templateString 包含连接到主文件中的样式表和图像的 html 内容。
String itemURL = "file://" + itemPath;
testWV.loadDataWithBaseURL(itemURL, templateString, "text/html", "UTF-8", "about:blank");
我面临的问题是锚链接根本没有响应。
我注意到如果 itemURL 为空,或者如果我使用 loadData 而不是 loadDataWithBaseURL,链接可以工作,但我失去了图像的连接和通过 itemURL 连接的样式。
请注意,webview 可见性始终设置为可见。添加我已将以下功能添加到 webview
this.getSettings().setJavaScriptEnabled(true);
this.requestFocusFromTouch();
this.setVerticalScrollBarEnabled(false);
this.setHorizontalScrollBarEnabled(false);
this.getSettings().setSupportZoom(true);
this.getSettings().setBuiltInZoomControls(true);
this.getSettings().setDisplayZoomControls(false);
this.getSettings().setAllowContentAccess(true);
this.getSettings().setAllowFileAccess(true);
this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
this.getSettings().setAllowFileAccessFromFileURLs(true);
this.getSettings().setAllowUniversalAccessFromFileURLs(true);
这是为 webview 初始化的 onTouch 方法:
this.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
WebView.HitTestResult hr = ((WebView)v).getHitTestResult();
System.out.println("getExtra: "+hr.getExtra());
// getExtra always gives null when webview loaded with loadDataWithBaseURL while it should give the url of the link pressed when the user touches a link
return false;
}
});
如果需要更多代码,我可以分享。
解决方案
设置WebViewClient
为您的webView
并加载数据loadDataWithBaseURL
并传递您的基本网址
这将有助于将锚 url 加载到webview
webview.getSettings().setJavaScriptEnabled(true);
webview.requestFocusFromTouch();
webview.setWebViewClient(new MyWebClient());
这是WebViewClient
上课
class MyWebClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, final String url) {
}
}
推荐阅读
- python - Python字符串交换格式
- linux - 在 RHEL Linux 机器中查找 sudo su jenkins 出现的命令
- php - php - Codeigniter Rest api 简单的 CRUD
- python - 如何将字典中的值转换为逗号分隔的字符串,字典也存在于列表中
- ruby-on-rails - 从表单创建连接表的新记录。选择输入
- angular - 在组件中多次使用时,带/不带选择器的 ng-content 不显示内容
- python - 类型错误:isfile() 缺少 1 个必需的位置参数:'remotepath'
- java - 我正在尝试链接包中的 JSP 和 Java 文件,因为我在 Conn.java 类中建立了 JDBC 连接
- python - 获取类成员名称作为字符串
- json - 用于创建用户并添加到服务台的 Powershell 脚本突然无法正常工作