Android(java)学习笔记90:TextView 添加超链接(两种实现方式)

1. TextView添加超链接:

TextView添加超链接有两种方式,它们有区别于WebView:

(1)方式1:

        LinearLayout layout = new LinearLayout(this);
        LinearLayout.LayoutParams  params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        TextView textView = new TextView(this);
        String html = "有问题:\n";
        html +="<a href='http://www.baidu.com'>百度一下</a>";//注意这里必须加上协议号,即http://
        //public static Spanned fromHtml(String source):这里返回的是Spanned,由于这个Spanned是继承自CharSequence
        //所以,可以不经过类型转化直接用CharSequence接收Spanned类型
        CharSequence charSequence = Html.fromHtml(html);
        textView.setText(charSequence); 
        //设置该句使文本TextView的超连接起作用,LinkMovementMethod.getInstance():返回一个MovementMethod实例
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        layout.addView(textView); 
        this.setContentView(layout,params); 

(2)方式2:

        LinearLayout layout = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        TextView textView = new TextView(this);
        String html = "有问题:\n";
        html+="www.baidu.com";//这里即使不加协议HTTP;也能自动被系统识别出来
        textView.setText(html);
        //这里即使不加协议好HTTP;也能自动被系统识别出来
        textView.setAutoLinkMask(Linkify.ALL);
        //设置该句使文本TextView的超连接起作用
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        layout.addView(textView);
        this.setContentView(layout,params);

TextView.setAutoLinkMask(Linkify.ALL);

Linkify.ALL:all available patterns(匹配所有)

Linkify.MAP_ADDRESSES :street addresses should be matched in methods(匹配街道地址编号)

Linkify.PHONE_NUMBERS :phone numbers(匹配电话号码)

Linkify.EMAIL_ADDRESSES : email addresses(匹配Email地址)

Linkify.WEB_URLS : web URLs  (匹配Web网址)

 

posted on 2015-08-10 15:52  鸿钧老祖  阅读(377)  评论(0编辑  收藏  举报

导航