android - 如何更改 TextView 上的某些特定字符?

标签 android spannable

我需要更改 TextView 中每个元音字母的颜色。 例如我有 ("a", "e", "i", "o", "u") 并且我需要它们是这样的 -

GR<font color='green'>EE</font>N C<font color='green'>O</font>L<font color='green'>O</font>R

我正在尝试这个:

    if(text.contains("o")){
        SpannableString spanText = new SpannableString(text);

        // make "text" (characters pos-1 to pos) red
        spanText.setSpan(new ForegroundColorSpan(Color.GREEN), text.indexOf("o") - 1, text.indexOf("o"), 0);
        labelTextView.setText(spanText, TextView.BufferType.SPANNABLE);
    }

但我需要更困难地更改 SpannableString,但不知道如何更改。 有什么建议吗?

最佳答案

您可以将您的个人颜色包装在 html 颜色标签中,并使用 Html.fromHtml(String string);获取您的跨度。

如果您需要更困难的字符串颜色连接,您可以定义一个方法来将字符串的各个部分包装在您的 html 中并连接结果。

编辑:

我确信有一种更有效的方法可以做到这一点,但这是行得通的。如果您想映射多种不同的颜色,则必须扩展逻辑。

public String wrapVowelsInColor(String input){
    final List<String> VOWELS = new ArrayList<>(Arrays.asList(new String[] {"a", "A", "e", "E" ,"i", "I", "o", "O", "u", "U"}));

    final char[] mChars = input.toCharArray();
    final int count = mChars.length;
    final StringBuilder builder = new StringBuilder(count);
    for(int i = 0; i < count; i++){
        String current = String.valueOf(mChars[i]);
        if(VOWELS.contains(current)){
            builder.append(wrapInColor("blue", current)));
        } else {
            builder.append(current);
        }
    }

    return builder.toString();
}

public String wrapInColor(String color, String toWrap){
    return String.format("<font color='%s'>%s</font>", color, toWrap);
}

输入:

String testString = "My test string for coloring vowels";

输出:

My t<font color='blue'>e</font>st str<font color='blue'>i</font>ng f<font color='blue'>o</font>r c<font color='blue'>o</font>l<font color='blue'>o</font>r<font color='blue'>i</font>ng v<font color='blue'>o</font>w<font color='blue'>e</font>ls

然后只需在输出上运行 Html.fromHtml(String string),然后再在 TextView 上设置跨度。

关于android - 如何更改 TextView 上的某些特定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654914/

相关文章:

android - 使用 DrawerLayout 打开 Activity 时如何消除延迟?

Android Sqlite 存储限制

android - 具有不同 textSize 的 TextView

java - 提高设置 TextView RecyclerView 时的跨度/可跨度性能

android - 在android TextView中缩进项目符号行

android - HistoryRecord 的 Activity 空闲超时

android - 在Android中的表格布局中设置等宽的列

java - Android消息应用架构硬件要求

android - spannableStringBuilder 无法在单个 TextView 中使用多个跨度

具有多个点击事件的 Android TextView