欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android TextView显示html样式的文字

程序员文章站 2023-12-20 13:58:28
先给大家说下项目需求: textview显示一段文字,格式为:白雪公主(姓名,字数不确定)向您发来了2(消息个数,不确定)条消息 这段文字中名字和数字的长度是不确定的,...

先给大家说下项目需求:

textview显示一段文字,格式为:白雪公主(姓名,字数不确定)向您发来了2(消息个数,不确定)条消息

这段文字中名字和数字的长度是不确定的,还要求名字和数字各自有各自的颜色。

就想到了用

html.fromhtml(string str)来实现。

看方法名很简单,就是可以显示字符串str对应的html格式的文本

比如:

html.fromhtml(<font color='red' size='24'>你好</font>" )

就将你好以html格式显示了,红色字体 大小24

那么通过一个小demo看下这个方法的简单使用:

我有三个字符串,字符串中姓名、数字长度都是不同的,实现让姓名显示红色,数字显示蓝色,其他文字显示默认灰色的效果

先写布局文件,三个textview

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
android:paddingbottom="@dimen/activity_vertical_margin"
android:gravity="center"
android:orientation="vertical"
tools:context=".mainactivity">
<textview
android:id="@+id/html_text"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<textview
android:id="@+id/html_text2"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<textview
android:id="@+id/html_text3"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</linearlayout>

然后activity 的oncreate()方法

@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
textview = (textview) findviewbyid(r.id.html_text);
textview2 = (textview) findviewbyid(r.id.html_text2);
textview3 = (textview) findviewbyid(r.id.html_text3);
names = new arraylist<>();
counts = new arraylist<>();
message = new arraylist<>();
names.add("奥特曼");
names.add("白雪公主与七个小矮人");
names.add("沃德天·沃纳陌帅·帅德·布耀布耀德 ");
counts.add(1);
counts.add(123);
counts.add(9090909);
for (int i = 0; i < 3; i++) {
message.add("<font color='red' size='20'>"+names.get(i)+"</font>"+"向您发来"+
"<font color='blue' size='30'>"+counts.get(i)+"</font>"+"条信息");
}
textview.settext(html.fromhtml(message.get(0)));
textview2.settext(html.fromhtml(message.get(1)));
textview3.settext(html.fromhtml(message.get(2)));
}

看下效果图,是不是很简单,只要简单的会html 就可实现这种效果

Android TextView显示html样式的文字

以上内容是小编给大家分享的android textview显示html样式的文字,希望本文分享能够帮助到大家。

上一篇:

下一篇: