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

时间:2011-08-28 15:42:53

标签: android string colors textview

我正在寻找一种方法来改变TextViewActivity中单个单词的文字颜色。

例如,有了这个:

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

如何将next文字的颜色更改为红色?

9 个答案:

答案 0 :(得分:154)

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

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

但这会要求你在(如果?)想要改变颜色时重建TextView,这可能会造成麻烦。

答案 1 :(得分:70)

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);

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

答案 2 :(得分:26)

Use SpannableStringBuilder like this :

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);

答案 3 :(得分:2)

如果要更改String文本中特定TextView的所有实例的状态(不区分大小写),可以使用StringBuilderSpannableString之类的这样:

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);

}

  • 将整个TextView文字存储在StringBuilder
  • 将搜索到的字符串存储在StringBuilder
  • TextView
  • 中的wholre SpannableString文字存储起来
  • 进行简单的操作,找到String文本中的所有TextView个实例,并在到达时更改它们。
  • TextView的文字值设置为SpannableString

答案 4 :(得分:1)

对于长字符串,你可以使用它:

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

答案 5 :(得分:1)

我在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)
            }

我如何使用它:

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

答案 6 :(得分:0)

使用情况:

makeTextBold("Your order is accepted","accepted", textView);
makeTextBold("Your order is canceled","canceled", textView);

功能

public static void makeTextBold(String sentence, String word, AppCompatTextView textView) {
    SpannableStringBuilder builder = new SpannableStringBuilder();
    int startIndex = sentence.indexOf(word.toLowerCase().trim());
    int endIndex = startIndex + word.toLowerCase().trim().length();
    SpannableString spannableString = new SpannableString(sentence);
    StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
    spannableString.setSpan(boldSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //To make text Bold
    spannableString.setSpan(new ForegroundColorSpan(Color.RED), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //To change color of text
    builder.append(spannableString);
    textView.setText(builder, TextView.BufferType.SPANNABLE);
}

答案 7 :(得分:0)

我认为这更具可读性 用于为字符串中的单词着色 也许还可以提高一点效率,因为您只需编写一次

    String str  = YOUR_STRING
    Spannable s = new SpannableString(str);
    int start = str.indexOf(err_word_origin);
    int end =  start + err_word_origin.length();
    s.setSpan(new ForegroundColorSpan(Color.BLUE), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    YOUR_TEXT_VIEW.setText(s , TextView.BufferType.SPANNABLE);

答案 8 :(得分:0)

我的解决方案扩展:

           Row(
          children: [
            Expanded(
              child: SizedBox(
                height: 80,
                child: category.categoryList != null ? category.categoryList.length > 0 ? ListView.builder(
                  itemCount: category.categoryList.length,
                  padding: EdgeInsets.only(left: Dimensions.PADDING_SIZE_SMALL),
                  physics: BouncingScrollPhysics(),
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(right: Dimensions.PADDING_SIZE_SMALL),
                      child: InkWell(
                        onTap: () => Navigator.pushNamed(context, Routes.getCategoryRoute(
                          category.categoryList[index].id, category.categoryList[index].image,
                          category.categoryList[index].name.replaceAll(' ', '-'),
                        )),
                        child: Column(children: [
                          ClipOval(
                            child: FadeInImage.assetNetwork(
                              placeholder: Images.placeholder_image,
                              image: Provider.of<SplashProvider>(context, listen: false).baseUrls != null
                                  ? '${Provider.of<SplashProvider>(context, listen: false).baseUrls.categoryImageUrl}/${category.categoryList[index].image}':'',
                              width: 65, height: 65, fit: BoxFit.cover,
                               ),
                          ),

                          Text(
                            category.categoryList[index].name,
                            style: rubikMedium.copyWith(fontSize: Dimensions.FONT_SIZE_SMALL),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),

                        ]),
                      ),
                    );
                  },
                ) : Center(child: Text(getTranslated('no_category_avl', context))) : CategoryShimmer(),
              ),
            ),
           ResponsiveHelper.isMobile(context)? SizedBox(): category.categoryList != null ? Column(
              children: [
                InkWell(
                  onTap: (){
                    showDialog(context: context, builder: (con) => Dialog(
                      child: Container(height: 550, width: 600, child: CategoryPopUp())
                    ));
                  },
                  child: Padding(
                    padding: EdgeInsets.only(right: Dimensions.PADDING_SIZE_SMALL),
                    child: CircleAvatar(
                      radius: 35,
                      backgroundColor: Theme.of(context).primaryColor,
                      child: Text(getTranslated('view_all', context), style: TextStyle(fontSize: 14,color: Colors.white)),
                    ),
                  ),
                ),
                SizedBox(height: 10,)
              ],
            ): CategoryAllShimmer()
          ],
        ),

用法

    fun coloredText(
    baseText: String,
    coloredText: String,
    targetColor: Int
): SpannableStringBuilder {
    val transformText = "$baseText $coloredText"
    return SpannableStringBuilder(transformText).apply {
        setSpan(
            ForegroundColorSpan(targetColor),
            transformText.indexOf(coloredText),
            (transformText.indexOf(coloredText) + coloredText.length),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
    }
}