是否有可能为一个TextView内的不同文本块设置多个样式?

例如,我将文本设置如下:

tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);

是否可以为每个文本元素设置不同的样式?例如,行1加粗,字1斜体等。

开发者指南的常见任务和如何在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);

但这使用了文本中的显式位置编号。有更干净的方法吗?


当前回答

Kotlin中最干净的方法是使用Span

val myTitleText = "Hello World"

val spannable = SpannableString(myTitleText)
spannable.setSpan(
    TextAppearanceSpan(context, R.style.myFontMedium),
    0,
    4,
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
tvMytitle.text = spannable

来自:Hello Word

收件人:Hello World

其他回答

如果有人想知道如何做到这一点,这里有一种方法:(再次感谢马克!)

mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" + 
            "<small>" + description + "</small>" + "<br />" + 
            "<small>" + DateAdded + "</small>"));

关于这个方法支持的非官方标签列表,请参考这个链接或这个问题:Android TextView支持哪些HTML标签?

在网页底部使用一个辅助的可扩展类作为Android字符串资源共享。你可以通过创建charsquences并给它们一个样式来实现。

但在他们给我们的例子中,只是粗体,斜体,甚至是彩色文本。我需要在aCharSequence中包装几个样式,以便在TextView中设置它们。所以这个类(我命名为charsequencestyle),我只是添加了这个函数。

public static CharSequence applyGroup(LinkedList<CharSequence> content){
    SpannableStringBuilder text = new SpannableStringBuilder();
    for (CharSequence item : content) {
        text.append(item);
    }
    return text;
}

在视图中我添加了这个。

            message.push(postMessageText);
            message.push(limitDebtAmount);
            message.push(pretMessageText);
            TextView.setText(CharSequenceStyles.applyGroup(message));

我希望这对你有帮助!

如果你想在xml中添加样式文本,你可以创建一个自定义视图扩展TextView并覆盖setText():

public class HTMLStyledTextView extends TextView
{
    public HTMLStyledTextView(Context context) {
        super(context);
    }

    public HTMLStyledTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HTMLStyledTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type)
    {
       super.setText(Html.fromHtml(text.toString()), type);
    }
}

然后,你可以像这样使用它(用你的包名替换PACKAGE_NAME):

<PACKAGE_NAME.HTMLStyledTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="<![CDATA[
        <b>Bolded Text:</b> Non-Bolded Text
    ]]>"
/>

支持的标签列表如下:

如果使用字符串资源,则可以添加一些简单的样式,例如使用HTML标记的粗体或斜体。目前支持的标签有:B(粗体)、I(斜体)、U(下划线)、TT(单行)、BIG、SMALL、SUP(上标)、SUB(下标)和STRIKE(划线)。例如,在res/values/strings.xml中,你可以这样声明: <资源> <string id="@+id/styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> > < /资源

(来自http://developer.android.com/guide/faq/commontasks.html#selectingtext - Web Archive链接,<资源>错别字是在原始!)

它还表明在简单的情况下并不真正需要Html.fromHtml。

是的,可以使用SpannedString。如果你正在使用Kotlin,使用core-ktx会变得更容易,因为它提供了一种领域特定语言(DSL)来做这件事:

    val string: SpannedString = buildSpannedString {
        bold {
            append("1111")
        }
        append("Devansh")     
    }

它提供的更多选项有:

append("Hello There")
bold {
    append("bold")
    italic {
        append("bold and italic")
        underline {
            append("then some text with underline")
        }
    }
}

最后,你只需:

textView.text = string