Android之TextView超链接

在TextView添加超链接,有两种方式,第一种通过HTML格式化你的网址,一种是设置autolink,让系统自动识别超链接,以下代码示例:

第一种方式:

   public class MainActivity extends Activity { 
        @Override 
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        } LinearLayout layout = new LinearLayout(this);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 
        TextView textView = new TextView(this); 
        String html = "有问题:\n"; html+="<a href="http://www.baidu.com">百度一下</a>";
//注意这里必须加上协议号,即http://。 
//否则,系统会以为该链接是activity,而实际这个activity不存在,程序就崩溃。
         CharSequence charSequence = Html.fromHtml(html); 
        textView.setText(charSequence); textView.setMovementMethod(LinkMovementMethod.getInstance()); 
        layout.addView(textView); this.setContentView(layout,params); 
    }

第二种方式:

    public class MainActivity extends Activity {
        @Overrideprotected
        void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            LinearLayout layout = new LinearLayout(this);
            LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            TextView textView = new TextView(this);
            String html = "有问题:\n";
            html += "www.baidu.com";//这里即使不加协议好HTTP;也能自动被系统识别出来。 
            textView.setText(html);
            textView.setAutoLinkMask(Linkify.ALL);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            layout.addView(textView);
            this.setContentView(layout, params);
        }

最后,以html显示超链接,必须写全url。以setAutoLinkMask(Linkify.ALL)可以不用不用写全,就能自动识别出来。

这两种方法,都得设置一下setMovementMethod,才会有效。

另外setAutoLinkMask不仅 识别超链接,包括电话号码之类等都能识别成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

generallizhong

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值