美文网首页
基于Kotlin MVVM框架 实现预览HTML链接内容的功能

基于Kotlin MVVM框架 实现预览HTML链接内容的功能

作者: 熊凯 | 来源:发表于2017-06-30 11:21 被阅读68次
  • 一般使用到IM sdk的童鞋,一般都会碰到,粘贴内容到聊天框的时候,如果是粘贴的内容包含了网页链接的时候,如果这个时候,能够识别到里面的链接,并且展示效果 这样是很炫酷的,当然这个思路是来自阿里的钉钉:

我们来看下钉钉的效果

image.png

看下我们实现的效果

image.png

看完效果,开始动手!!!

准备工作

思路

  • 在粘贴文字到聊天框中时候,检测是否包含网页连接地址
  • 获取到的链接地址 判断是否有效的链接
  • 实时获取链接中的内容 图片、标题、内容。
  • 显示效果。

工具

  • jsoup

准备

  • android studio
  • 添加依赖
 compile 'org.jsoup:jsoup:1.10.3'

开始撸代码

判断文字块中是否包含网页链接地址 ,如果有拿到 url集合

    public static List<String> extractUrls(String text) {
        List<String> containedUrls = new ArrayList<String>();
        String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
        Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
        Matcher urlMatcher = pattern.matcher(text);
        while (urlMatcher.find()) {
            containedUrls.add(text.substring(urlMatcher.start(0),
                    urlMatcher.end(0)));
        }
        return containedUrls;
    }

根据url地址 获取标题 内容 图片 (子线程操作,否则报错)

                JsoupPojo jsoupPojo = null;
                        try {
                            Document document = Jsoup.connect(_s).get();
                            if (document != null) {
                                jsoupPojo = new JsoupPojo();
                                jsoupPojo.title = document.title();
                                jsoupPojo.imgs = JsoupUtils.getImgs(document);
                                jsoupPojo.time = JsoupUtils.getTime(document);
                                jsoupPojo.content = document.body().text();
                                jsoupPojo.url = _s;
                            }

                        } catch (IOException _e) {
                            _e.printStackTrace();
                        } finally {
                            L.d("jsoupPojo :" + jsoupPojo.toString());
                        }


----jsoupPojo

    public String title;
    public List<String> imgs;
    public String time;
    public String content;
    public String briefContent;
    public String band; //哪个网站
    public String url; //哪个网站

自此拿到的了文字快中的链接的所有的信息。
怎么样显示到控件,使用了上一篇文章MVVM框架是非常简单的。(这里不做赘述)

Copyright (c) 2017 Copyright Holder All Rights Reserved.
原创文章,转载需说明出处,版权归作者所有。

相关文章

网友评论

      本文标题:基于Kotlin MVVM框架 实现预览HTML链接内容的功能

      本文链接:https://www.haomeiwen.com/subject/ogpbcxtx.html