Android使用HTML标签

如果一行文字出现了两种颜色,这个时候该怎么处理呢?TextView拼接?如果文字的行数不确定呢?

其实Android是有现成解决方案的,这就是HTML标记。在网页中我们为文字添加不同的标签,就能呈现不同的样式,非常方便。Android的TextView控件也是支持HTML标记的,不过多了点额外的操作。下面就是一个样例,设置了字体颜色并且在中间嵌了一张图片。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
* Created by hsji on 2015/8/5.
*/
public class extends Activity{
TextView content;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_html_string);
content = (TextView) findViewById(R.id.content);
* This methos is called when the HTML parser encounters an <img> tag.
* The source argument is the string from the "src" attribute;
* the return value should be a Drawable representation of the image or null for a generic replacement image.
* Make sure you call setBounds() on your Drawable if it doesn't already have its bounds set.
*/
Html.ImageGetter imageGetter = new Html.ImageGetter(){
public Drawable getDrawable(String source) {
Drawable drawable = null;
try {
drawable = getResources().getDrawable(Integer.parseInt(source));
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}catch (NumberFormatException e){
e.printStackTrace();
}
return drawable;
}
};
StringBuffer sb = new StringBuffer();
sb.append("<font color="#ff0000">我</font>")
.append("<img src=""+R.drawable.heart+""/>")
.append("<font color="#ff0000">董英</font>");
Spanned spanned = Html.fromHtml(sb.toString(),imageGetter,null);
content.setText(spanned);
}
}

下面是效果图: