1.使用jsoup Document document = Jsoup.connect(url).timeout(9000).get(); 来得到网页内容
2.用webView.loadDataWithBaseURL (null, data, "text/html", "utf-8",null); data 是指网页内容,只包含<body> </body>标签中的就可以
3.js和原生互调用
// 注入js函数监听
private void addImageClickListner() {
// 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去
webView.loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName(\"img\"); " +
"for(var i=0;i<objs.length;i++) " +
"{"
+ " objs[i].οnclick=function() " +
" { "
+ " window.imagelistner.openImage(this.src); " +
" } " +
"}" +
"})()");
}
private void initWebView() {
webView = (WebView)findViewById(R.id.wb_details);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
if (!TextUtils.isEmpty(news_url)) {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);//设置可以运行JS脚本
// settings.setTextZoom(120);//Sets the text zoom of the page in percent. The default is 100.
settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
// settings.setUseWideViewPort(true); //打开页面时, 自适应屏幕
// settings.setLoadWithOverviewMode(true);//打开页面时, 自适应屏幕
settings.setSupportZoom(false);// 用于设置webview放大
settings.setBuiltInZoomControls(false);
webView.setBackgroundResource(R.color.transparent);
// 添加js交互接口类,并起别名 imagelistner
webView.addJavascriptInterface(new MyJavascriptInterface(this),"imagelistner");
webView.setWebChromeClient(new MyWebChromeClient());
webView.setWebViewClient(new MyWebViewClient());
new MyAsnycTask().execute(news_url, news_title, news_source + " " +news_date);
}
}
// js通信接口
public class MyJavascriptInterface {
private Context context;
public MyJavascriptInterface(Context context) {
this.context = context;
}
@JavascriptInterface //解决api17以上的问题
public void openImage(String img) {
//
String[] imgs = img.split(",");
ArrayList<String> imgsUrl = new ArrayList<String>();
for (String s : imgs) {
imgsUrl.add(s);
Log.i("图片的URL>>>>>>>>>>>>>>>>>>>>>>>", s);
}
Intent intent = new Intent();
intent.putStringArrayListExtra("infos", imgsUrl);
intent.setClass(context, ImageShowActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}