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

来源:互联网 发布:人工智能取代的职业 编辑:程序博客网 时间:2024/05/16 14:20

首先在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());
原创粉丝点击