如何在Android中为TextView的部分文本添加颜色?

18

我正在尝试改变TextView中某些词(搜索结果)的颜色。我尝试使用ANSI颜色,像这样:

text.setText("\u001B31;1m" + "someText");

但是它没有起作用。我该怎么做才能实现这个?


请参考以下链接:https://dev59.com/qG445IYBdhLWcg3wXZIy - live-love
4个回答

32

这会对你有所帮助

Spannable WordtoSpan = new SpannableString("I know just how to whisper");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 13, 
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(WordtoSpan);

5,13 是字符的长度。 - RajaReddy PolamReddy
4
你是指开始和结束索引吗? - Marek
你想为哪个部分着色文本?请指定需要着色的文本起始点和结束点。 - RajaReddy PolamReddy

4

您正在寻找 TextAppearanceSpan 和 'SpannableString',更清晰的工作流程如下:

  1. 从源字符串创建 SpannableString
  2. 通过对 SpannableString 的 setSpan 方法创建 TextAppearanceSpan,并设置它
  3. 使用 SpannableString 作为参数调用 textView.setText 方法

2

我知道我来晚了,但我认为这将有助于未来的访问者。

您可能想在布局XML上设置部分文本颜色,而不是使用Java代码。因此,根据此线程上以前的答案,我创建了一个小类来实现此功能。

1 - 首先,让我们创建我们的组件

package yourpackagehere.component;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;

import yourpackagehere.R;

public class FontSpannableTextView extends TextView {

    public FontSpannableTextView(Context context) {
        super(context);
    }

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

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

    private void setColorPartialString(Context context, AttributeSet attrs) {
        if (isInEditMode()) {
            return;
        }
        String partialText = null;
        int partialTextColor = Integer.MIN_VALUE;

        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FontSpannableTextView);
            for (int i = 0; i < a.getIndexCount(); i++) {
                int attr = a.getIndex(i);
                switch (attr) {
                    case R.styleable.FontSpannableTextView_fontspannabletextview_partialText:
                        partialText = a.getString(attr);
                        break;
                    case R.styleable.FontSpannableTextView_fontspannabletextview_partialTextColor:
                        partialTextColor = a.getColor(attr, Color.BLACK);
                        break;
                }
            }
            a.recycle();
        }

        if (partialText != null && partialTextColor != Integer.MIN_VALUE) {
            String wholeText = getText().toString();
            Spannable spannable = new SpannableString(wholeText);
            spannable.setSpan(new ForegroundColorSpan(partialTextColor),
                    wholeText.indexOf(partialText),
                    wholeText.indexOf(partialText) + partialText.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            setText(spannable);
        } else {
            Log.e("YOURTAGHERE","You must provide both partialText and partialTextColor values");
        }
    }
}

2 - on attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="FontSpannableTextView">
        <attr name="fontspannabletextview_partialText" format="string" />
        <attr name="fontspannabletextview_partialTextColor" format="color" />
    </declare-styleable>
</resources>

3 - 让我们在测试布局中使用它

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">


    <yourpackagehere.component.FontSpannableTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" <!-- Hello world! -->
        android:layout_margin="25dp"
        app:fontspannabletextview_partialText="@string/world" <!-- world! -->
        app:fontspannabletextview_partialTextColor="@color/tutorial_yellow"
        android:textSize="40sp"
        />

</LinearLayout>

示例:

在此输入图片描述

(注:该示例为IT技术相关内容,涉及HTML标签)

这是一个优雅的解决方案。我从十年前开始就一直在Android上工作,但即使在2020年,这似乎仍然是Android中TextView的一个主要问题。 - JaydeepW

2
您也可以像下面的例子一样使用HTML:

您可以像下面的例子一样使用HTML:

string = "<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>";
textView.setText(Html.fromHtml(string));

不使用额外变量(一行解决方案):

textView.setText(Html.fromHtml("<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>"));

这是一个很简单且易于理解的解决方案 :)


Html.fromHtml(string)现在已经被弃用,请更新您的答案。 - GS Nayma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接