android 如何在同一部分文本上设置TextView文本的多个跨度?

6rqinv9w  于 2023-05-15  发布在  Android
关注(0)|答案(5)|浏览(135)

假设我有下一个文本:
Hello stackOverflow
我希望将第二个单词设置为RelativeSizeSpan(设置相对字体大小)和TextAppearanceSpan(设置文本颜色),如何合并它们?
我所知道的是,我可以选择其中一个,例如使用下面的代码:

final SpannableString textToShow = new SpannableString("Hello stackOverflow");
textToShow.setSpan(new RelativeSizeSpan(1.5f), textToShow.length() - "stackOverflow".length(),textToShow.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(textToShow);

但我还需要设置颜色,甚至添加其他跨越类的其他功能...
我能做什么?

laik7k3q

laik7k3q1#

只需设置附加跨距。它们将在必要时重叠/合并。这段代码适合我:

final SpannableString text = new SpannableString("Hello stackOverflow");
text.setSpan(new RelativeSizeSpan(1.5f), text.length() - "stackOverflow".length(), text.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new ForegroundColorSpan(Color.RED), 3, text.length() - 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(text);
fv2wmkja

fv2wmkja2#

我知道这是对一个已经有答案的问题的新回答,但我想分享一个我做的实用程序类,它使这项任务更容易。

Java版本

public class SimpleSpanBuilder {
    private class SpanSection{
        private final String text;
        private final int startIndex;
        private final CharacterStyle[] styles;

        private SpanSection(String text, int startIndex,CharacterStyle... styles){
            this.styles = styles;
            this.text = text;
            this.startIndex = startIndex;
        }

        private void apply(SpannableStringBuilder spanStringBuilder){
            if (spanStringBuilder == null) return;
            for (CharacterStyle style : styles){
                spanStringBuilder.setSpan(style, startIndex, startIndex + text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }
    }

    private List<SpanSection> spanSections;
    private StringBuilder stringBuilder;

    public SimpleSpanBuilder(){
        stringBuilder = new StringBuilder();
        spanSections = new ArrayList<>();
    }

    public SimpleSpanBuilder append(String text,CharacterStyle... styles){
        if (styles != null && styles.length > 0) {
            spanSections.add(new SpanSection(text, stringBuilder.length(),styles));
        }
        stringBuilder.append(text);
        return this;
    }

    public SimpleSpanBuilder appendWithSpace(String text,CharacterStyle... styles){
        return append(text.concat(" "),styles);
    }

    public SimpleSpanBuilder appendWithLineBreak(String text,CharacterStyle... styles){
        return append(text.concat("\n"),styles);
    }

    public SpannableStringBuilder build(){
        SpannableStringBuilder ssb = new SpannableStringBuilder(stringBuilder.toString());
        for (SpanSection section : spanSections){
            section.apply(ssb);
        }
        return ssb;
    }

    @Override
    public String toString() {
        return stringBuilder.toString();
    }
}

用法:

SimpleSpanBuilder ssb = new SimpleSpanBuilder();
ssb.appendWithSpace("Hello");
ssb.append("StackOverflow",new ForegroundColorSpan(Color.RED),new RelativeSizeSpan(1.5));
textView.setText(ssb.build());

Kotlin版本

class SimpleSpanBuilder() {

    class Span {
        private var startIndex: Int = 0
        internal var text: String
        private var styles: Array<out CharacterStyle>

        internal constructor(index: Int, text: String, vararg styles: CharacterStyle) {
            this.startIndex = index
            this.text = text
            this.styles = styles
        }

        constructor(text: String, vararg styles: CharacterStyle) : this(0, text, *styles)

        internal fun setIndex(index: Int): Span {
            return Span(index, this.text, *this.styles)
        }

        internal fun apply(spanStringBuilder: SpannableStringBuilder?) {
            if (spanStringBuilder == null) return
            for (style in styles) {
                spanStringBuilder.setSpan(
                    style,
                    startIndex,
                    startIndex + text.length,
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE
                )
            }
        }
    }

    private val spanSections = mutableListOf<Span>()
    private val stringBuilder = StringBuilder()

    constructor(text: String, vararg styles: CharacterStyle) : this() {
        plus(Span(text, *styles))
    }

    operator fun plus(span: SimpleSpanBuilder.Span): SimpleSpanBuilder {
        spanSections.add(span.setIndex(stringBuilder.length))
        stringBuilder.append(span.text)
        return this
    }

    fun build(): SpannableStringBuilder {
        val ssb = SpannableStringBuilder(stringBuilder.toString())
        for (section in spanSections) {
            section.apply(ssb)
        }
        return ssb
    }

    override fun toString(): String {
        return stringBuilder.toString()
    }
}

用法

var ssb = SimpleSpanBuilder("Hello ",ForegroundColorSpan(Color.BLUE))
ssb += SimpleSpanBuilder.Span(
    "StackOverflow",
    ForegroundColorSpan(Color.RED),
    RelativeSizeSpan(1.5f)
)

textView.text = ssb.build()
t5fffqht

t5fffqht3#

最简单的方法?

textView.setText("I love coding");

setHighLightedText(textView,"coding");

使用下面的方法-

public void setHighLightedText(TextView tv, String textToHighlight) {
    String tvt = tv.getText().toString();
    int ofe = tvt.indexOf(textToHighlight, 0);
    Spannable wordToSpan = new SpannableString(tv.getText());

    for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
        ofe = tvt.indexOf(textToHighlight, ofs);
        if (ofe == -1)
            break;
        else {
            // you can change or add more span as per your need
            wordToSpan.setSpan(new RelativeSizeSpan(2f), ofe,ofe + textToHighlight.length(), 0); // set size
            wordToSpan.setSpan(new ForegroundColorSpan(Color.RED), ofe, ofe + textToHighlight.length(), 0);// set color
            tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
        }
    }
}
yhived7q

yhived7q4#

Kotlin可以通过SpannableStringBuilder上的扩展来帮助做到这一点:

fun SpannableStringBuilder.spansAppend(
    text: CharSequence,
    flags: Int,
    vararg spans: Any
): SpannableStringBuilder {
    val start = length
    append(text)

    spans.forEach { span ->
        setSpan(span, start, length, flags)
    }

    return this
}

用法示例:

val builder = SpannableStringBuilder()
builder.append("Start of string ")
builder.spansAppend(
    "text spanned",
    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
    RelativeSizeSpan(1.1f),
    ForegroundColorSpan(Color.RED)
)
q3qa4bjr

q3qa4bjr5#

我在Java中写了一个示例函数来同时追加多个span:

private void append(SpannableStringBuilder builder, CharSequence text, int flags, Object... spans) {
    int start = builder.length();
    builder.append(text);
    if (spans != null) {
        for (Object span :  spans) {
            if (span != null)
                builder.setSpan(span, start, builder.length(), flags);
        }
    }
}

使用这个方法很简单:

SpannableStringBuilder builder = new SpannableStringBuilder();
append(builder, "test", Spannable.SPAN_EXCLUSIVE_EXCLUSIVE, new ForegroundColorSpan(Color.WHITE), new StyleSpan(android.graphics.Typeface.BOLD));

相关问题