组装字符串时如何为TextView生成样式化文本? [英] How to generate Styled text for TextView while assembling string?

查看:79
本文介绍了组装字符串时如何为TextView生成样式化文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TextView,它将保存一个样式化的多行字符串。随着数据一点一点地从不同的源中提取,此文本逐行生成。抓取每个字段时,在新行上向TextView添加一个粗体标头,然后在新行上以斜体添加该字段的数据。

I have a TextView that will hold a styled, multiline string. This text is generated line by line as the data is drawn from different sources bit by bit. As I grab each field, I add a Bold header to the TextView on a new line, then I add the data for that field in italics on a new line.

示例格式:

到期日期

2010年7月22日

课程

CSC 350

我可以这样设置样式:

Spannable str = (Spannable) textview.getText();

str.setSpan(new StyleSpan(android.graphics.Typeface.Bold), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.Italic), 8, 21, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.Bold), 21, 27, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.Italic), 27, 33, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

但这需要在运行时知道每个文本段的长度,这是很难处理的,因为可以添加到textview的可变数量的数据字段。

But that requires knowing the length of each section of text at runtime which is simply unmanageable since there is a variable number of data fields that could be added to the textview.

如何在添加每条文本时添加样式,而不是在所有文本

How can I add the styling as I'm adding each piece of text instead of after all the text has been added?

推荐答案

< b> 标记您的字符串和< i> 标记,然后使用 Html.fromHtml(String)返回您要查找的Spannable。

Mark your string up with <b> and <i> tags as appropriate and then use the Html.fromHtml(String) to return the Spannable you are looking for.

这篇关于组装字符串时如何为TextView生成样式化文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆