是否可以为 TextView 中的不同文本片段设置多种样式?
例如,我将文本设置如下:
tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);
是否可以为每个文本元素设置不同的样式?例如,line1 粗体,word1 斜体等。
开发人员指南的 常见任务和如何在 Android 中执行这些任务 包括 选择、突出显示或设置文本部分的样式:
// Get our EditText object. EditText vw = (EditText)findViewById(R.id.text); // Set the EditText's text. vw.setText("Italic, highlighted, bold."); // If this were just a TextView, we could do: // vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE); // to force it to use Spannable storage so styles can be attached. // Or we could specify that in the XML. // Get the EditText's internal text storage Spannable str = vw.getText(); // Create our span sections, and assign a format to each. str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
但这在文本中使用了明确的位置编号。有没有更清洁的方法来做到这一点?
原文由 Legend 发布,翻译遵循 CC BY-SA 4.0 许可协议
以防万一,有人想知道如何做到这一点,这是一种方法:(再次感谢马克!)
有关此方法支持的非官方标签列表,请参阅 此链接 或此问题: Android TextView 支持哪些 HTML 标签?