研究Android新闻类app webview中的图片点击

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);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值