如何编写带有超链接的TextView?

首先在XML中添加一个TextView:

 

        <TextView
            android:id="@+id/telcel_alert_infos"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"/>
 

 然后在Java代码中对这个TextView加入超链接:

        TextView textView = (TextView) findViewById(R.id.telcel_alert_infos);
        String webLinkText = getString(R.string.telcel_alert_infos);
        SpannableString sp = new SpannableString(webLinkText);
        sp.setSpan(new URLSpan("http://www.internet.telcel.com/"), 75, 94,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //对75到94的字符进行超链接到地址:http://www.internet.telcel.com/
        textView.setText(sp);
        textView.setMovementMethod(LinkMovementMethod.getInstance()); //这句一定要加

 

 strings.xml中定义的字符串:

    <string name="telcel_alert_infos">Algunas aplicaciones requieren conexión a datos. Te sugerimos contratar un paquete de Internet. Detalles con tu Operador de servicio.</string>

 

扩展:

 还可以修改TextView中的字体颜色,背景颜色等。

 

        TextView textView = (TextView) findViewById(R.id.telcel_alert_infos);
        String webLinkText = getString(R.string.telcel_alert_infos);
        SpannableString sp = new SpannableString(webLinkText);
        sp.setSpan(new URLSpan("http://www.internet.telcel.com/"), 75, 94,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//对75到94的字符进行超链接到地址:http://www.internet.telcel.com/
  sp.setSpan(new BackgroundColorSpan(Color.RED), 17, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //从17到19的字符,设置背景色为红色
        sp.setSpan(new ForegroundColorSpan(Color.YELLOW), 20, 24,
                Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //从20到24的字符,设置文字颜色为黄色
        sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 27, 29,
                Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //从27到29的字符,设置文字为斜体。
        textView.setText(sp);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值