在TextView中更改一个单词的文本颜色

时间:2023-02-13 03:35:18

I am looking for a way to change the color of a text of a single word in a TextView from within an Activity.

我正在寻找一种方法来改变活动中TextView中单个单词的文本颜色。

For example, with this:

例如,有了这个:

String first = "This word is ";
String next = "red"
TextView t = (TextView) findViewById(R.id.textbox);
t.setText(first + next);

How would I change the color of the next text to red?

如何将下一个文本的颜色更改为红色?

6 个解决方案

#1


140  

Easiest way I know is to just use html.

我知道最简单的方法就是使用html。

String first = "This word is ";
String next = "<font color='#EE0000'>red</font>";
t.setText(Html.fromHtml(first + next));

But this will require you to rebuild the TextView when (if?) you want to change the color, which could cause a hassle.

但是这需要你在(如果?)想要改变颜色时重建TextView,这可能会引起麻烦。

#2


66  

t.setText(first + next, BufferType.SPANNABLE);
Spannable s = (Spannable)t.getText();
int start = first.length();
int end = start + next.length();
s.setSpan(new ForegroundColorSpan(0xFFFF0000), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

you have to use spannable this will also allows you to increase some text's size, make it bold etc.... even put in some image.

你必须使用spannable这也可以让你增加一些文字的大小,使它变得粗体等....甚至放入一些图像。

#3


20  

Use SpannableStringBuilder like this :

像这样使用SpannableStringBuilder:

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

#4


2  

If you want to change the state of all the instances of a specific String inside a TextView text(case insensitive) you can use StringBuilders and SpannableString like this:

如果要更改TextView文本中特定String的所有实例的状态(不区分大小写),可以使用StringBuilders和SpannableString,如下所示:

StringBuilder textBuilder = new StringBuilder(myTextView.getText().toString());
StringBuilder searchedTextBuilder = new StringBuilder((mySearchedString));
SpannableString spannableString = new SpannableString(myTextView.getText().toString());

int counter = 0;
int index = 0;

for (int i = 0;i < textBuilder.length() - mySearchedString.length() - 1;i++)
{
    counter = 0;
    if (Character.toLowerCase(textBuilder.charAt(i)) == Character.toLowerCase(searchedTextBuilder.charAt(index)))
    {
        counter++;
        index++;
        for (int j = 1,z = i + 1;j < mySearchedString.length() - 1;j++,z++)
        {
            if (Character.toLowerCase(textBuilder .charAt(z)) == Character.toLowerCase(searchedTextBuilder .charAt(index)))
            {
                counter++;
                index++;
            }
            else
            {
                index++;
                if (index % mySearchedString.length() == 0)
                {
                    index = 0;
                }
                break;
             }
        }
        if (counter == mySearchedString.length() - 1) // A match
        {
            spannableString.setSpan(new ForegroundColorSpan(Color.RED), i,
                                i + mySearchedString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Do the change you want(In this case changing the fore ground color to red)
            index = 0;
            continue;
        }
        else
        {
            index = 0;
            continue;
        }
    }
}
myTextView.setText(spannableString);

}

}

  • Store the whole TextView text inside a StringBuilder.
  • 将整个TextView文本存储在StringBuilder中。
  • Store the searched string inside a StringBuilder.
  • 将搜索到的字符串存储在StringBuilder中。
  • Store the wholre TextView text inside a SpannableString
  • 将wholre TextView文本存储在SpannableString中
  • Make a simple operation to find all the String instances inside the TextView text and change them when reached.
  • 进行简单的操作以查找TextView文本中的所有String实例,并在到达时更改它们。
  • Set the text value of the TextView to the SpannableString.
  • 将TextView的文本值设置为SpannableString。

#5


1  

for long string you can use this:

对于长字符串,您可以使用此:

String help = getString(R.string.help);
help = help.replace("some word", "<font color='#EE0000'>some word</font>");
txtDesc.setText(Html.fromHtml(help));

#6


0  

I implemented a utility function in Kotlin for my own usecase and maybe useful for someone else.

我在Kotlin中实现了一个实用功能,用于我自己的用例,也许对其他人有用。

fun getCusomTextWithSpecificTextWithDiffColor(textToBold: String, fullText: String,
                                                  targetColor: Int) =
            SpannableStringBuilder(fullText).apply {
                setSpan(ForegroundColorSpan(targetColor),
                        fullText.indexOf(textToBold),
                        (fullText.indexOf(textToBold) + textToBold.length),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }

How I am using it:

我是如何使用它的:

context?.let {
        infoMessage.text = AppUtils.getCusomTextWithSpecificTextWithDiffColor(
                wordAsBold,
                completeSentence, ContextCompat.getColor(it, R.color.white))
    }

#1


140  

Easiest way I know is to just use html.

我知道最简单的方法就是使用html。

String first = "This word is ";
String next = "<font color='#EE0000'>red</font>";
t.setText(Html.fromHtml(first + next));

But this will require you to rebuild the TextView when (if?) you want to change the color, which could cause a hassle.

但是这需要你在(如果?)想要改变颜色时重建TextView,这可能会引起麻烦。

#2


66  

t.setText(first + next, BufferType.SPANNABLE);
Spannable s = (Spannable)t.getText();
int start = first.length();
int end = start + next.length();
s.setSpan(new ForegroundColorSpan(0xFFFF0000), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

you have to use spannable this will also allows you to increase some text's size, make it bold etc.... even put in some image.

你必须使用spannable这也可以让你增加一些文字的大小,使它变得粗体等....甚至放入一些图像。

#3


20  

Use SpannableStringBuilder like this :

像这样使用SpannableStringBuilder:

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

#4


2  

If you want to change the state of all the instances of a specific String inside a TextView text(case insensitive) you can use StringBuilders and SpannableString like this:

如果要更改TextView文本中特定String的所有实例的状态(不区分大小写),可以使用StringBuilders和SpannableString,如下所示:

StringBuilder textBuilder = new StringBuilder(myTextView.getText().toString());
StringBuilder searchedTextBuilder = new StringBuilder((mySearchedString));
SpannableString spannableString = new SpannableString(myTextView.getText().toString());

int counter = 0;
int index = 0;

for (int i = 0;i < textBuilder.length() - mySearchedString.length() - 1;i++)
{
    counter = 0;
    if (Character.toLowerCase(textBuilder.charAt(i)) == Character.toLowerCase(searchedTextBuilder.charAt(index)))
    {
        counter++;
        index++;
        for (int j = 1,z = i + 1;j < mySearchedString.length() - 1;j++,z++)
        {
            if (Character.toLowerCase(textBuilder .charAt(z)) == Character.toLowerCase(searchedTextBuilder .charAt(index)))
            {
                counter++;
                index++;
            }
            else
            {
                index++;
                if (index % mySearchedString.length() == 0)
                {
                    index = 0;
                }
                break;
             }
        }
        if (counter == mySearchedString.length() - 1) // A match
        {
            spannableString.setSpan(new ForegroundColorSpan(Color.RED), i,
                                i + mySearchedString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Do the change you want(In this case changing the fore ground color to red)
            index = 0;
            continue;
        }
        else
        {
            index = 0;
            continue;
        }
    }
}
myTextView.setText(spannableString);

}

}

  • Store the whole TextView text inside a StringBuilder.
  • 将整个TextView文本存储在StringBuilder中。
  • Store the searched string inside a StringBuilder.
  • 将搜索到的字符串存储在StringBuilder中。
  • Store the wholre TextView text inside a SpannableString
  • 将wholre TextView文本存储在SpannableString中
  • Make a simple operation to find all the String instances inside the TextView text and change them when reached.
  • 进行简单的操作以查找TextView文本中的所有String实例,并在到达时更改它们。
  • Set the text value of the TextView to the SpannableString.
  • 将TextView的文本值设置为SpannableString。

#5


1  

for long string you can use this:

对于长字符串,您可以使用此:

String help = getString(R.string.help);
help = help.replace("some word", "<font color='#EE0000'>some word</font>");
txtDesc.setText(Html.fromHtml(help));

#6


0  

I implemented a utility function in Kotlin for my own usecase and maybe useful for someone else.

我在Kotlin中实现了一个实用功能,用于我自己的用例,也许对其他人有用。

fun getCusomTextWithSpecificTextWithDiffColor(textToBold: String, fullText: String,
                                                  targetColor: Int) =
            SpannableStringBuilder(fullText).apply {
                setSpan(ForegroundColorSpan(targetColor),
                        fullText.indexOf(textToBold),
                        (fullText.indexOf(textToBold) + textToBold.length),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }

How I am using it:

我是如何使用它的:

context?.let {
        infoMessage.text = AppUtils.getCusomTextWithSpecificTextWithDiffColor(
                wordAsBold,
                completeSentence, ContextCompat.getColor(it, R.color.white))
    }