Установить цвет диапазона TextView в Android

Можно ли установить цвет всего текста в TextView?

Я хотел бы сделать что-то похожее на приложение Twitter, в котором часть текста синего цвета. Смотрите изображение ниже:

альтернативный текст

20 ответов

Решение

Другой ответ будет очень похожим, но не нужно будет задавать текст TextView дважды

TextView TV = (TextView)findViewById(R.id.mytextview01);

Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);

Вот небольшая справочная функция. Отлично подходит, когда у вас есть несколько языков!

private void setColor(TextView view, String fulltext, String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

Я всегда нахожу наглядные примеры, когда пытаюсь понять новую концепцию.

Фоновый цвет

SpannableString spannableString = new SpannableString("Hello World!");
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Цвет переднего плана

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

комбинирование

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Дальнейшее обучение

Если вы хотите больше контроля, вы можете проверить TextPaint учебный класс. Вот как это использовать:

final ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(final View textView) {
        //Your onClick code here
    }

    @Override
    public void updateDrawState(final TextPaint textPaint) {
        textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
        textPaint.setUnderlineText(true);
    }
};

Установите свой TextViewТекст можно охватить и определить ForegroundColorSpan для вашего текста.

TextView textView = (TextView)findViewById(R.id.mytextview01);    
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");          
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
textView.setText(wordtoSpan);

Другой способ, который можно использовать в некоторых ситуациях, - это установить цвет ссылки в свойствах представления, которое принимает Spannable.

Если ваш Spannable будет использоваться, например, в TextView, вы можете установить цвет ссылки в XML следующим образом:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="@color/your_color"
</TextView>

Вы также можете установить его в коде с помощью:

TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);
private SpannableString spannableString(SpannableString spannableString, int start, int end) {
    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

    spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}

SpannableString spannableString = new SpannableString("I don't like Hasina.");
spannableString(spannableString, 8, 14);
textView.setText(spannableString);

Выход:

Вот функция расширения Kotlin, которую я имею для этого

    fun TextView.setColouredSpan(word: String, color: Int) {
        val spannableString = SpannableString(text)
        val start = text.indexOf(word)
        val end = text.indexOf(word) + word.length
        try {
            spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text = spannableString
        } catch (e: IndexOutOfBoundsException) {
         println("'$word' was not not found in TextView text")
    }
}

Используйте его после того, как вы установили свой текст в TextView примерно так

private val blueberry by lazy { getColor(R.color.blueberry) }

textViewTip.setColouredSpan("Warning", blueberry)

Используя kotlin-ktx, вы можете легко этого добиться

              bindView?.oneTimePasswordTitle?.text = buildSpannedString {
        append("One Time Password ")
        inSpans(
            ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
        ){
            append(" (As Registered Email)")
        }

    }

Установите цвет для текста, передав строку и цвет:

private String getColoredSpanned(String text, String color) {
  String input = "<font color=" + color + ">" + text + "</font>";
  return input;
}

Установите текст в TextView / Button / EditText и т. Д., Вызвав код ниже:

TextView:

TextView txtView = (TextView)findViewById(R.id.txtView);

Получить цветную строку:

String name = getColoredSpanned("Hiren", "#800000");

Установить текст в TextView:

txtView.setText(Html.fromHtml(name));

Готово

Просто чтобы добавить к принятому ответу, так как все ответы, кажется, говорят о android.graphics.Color только: что, если цвет, который я хочу, определен в res/values/colors.xml?

Например, рассмотрим цвета Material Design, определенные в colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="md_blue_500">#2196F3</color>
</resources>

(android_material_design_colours.xml твой лучший друг)

Тогда используйте ContextCompat.getColor(getContext(), R.color.md_blue_500) где бы вы использовали Color.BLUE, чтобы:

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

будет выглядеть так:

wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Где я нашел это:

Есть фабрика для создания Spannable, и избегайте приведения, как это:

Spannable span = Spannable.Factory.getInstance().newSpannable("text");

Некоторые ответы здесь не актуальны. Потому что вы (в большинстве случаев) добавите настраиваемое действие клика на свою ссылку.

Кроме того, как указано в справке по документации, цвет вашей ссылки на составную строку будет иметь цвет по умолчанию. "Цвет ссылки по умолчанию - это основной цвет темы или android:textColorLink, если этот атрибут определен в теме".

Вот способ сделать это безопасно.

 private class CustomClickableSpan extends ClickableSpan {

    private int color = -1;

    public CustomClickableSpan(){
        super();
        if(getContext() != null) {
            color = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
        }
    }

    @Override
    public void updateDrawState(@NonNull TextPaint ds) {
        ds.setColor(color != -1 ? color : ds.linkColor);
        ds.setUnderlineText(true);
    }

    @Override
    public void onClick(@NonNull View widget) {
    }
}

Тогда использовать это.

   String text = "my text with action";
    hideText= new SpannableString(text);
    hideText.setSpan(new CustomClickableSpan(){

        @Override
        public void onClick(@NonNull View widget) {
            // your action here !
        }

    }, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    yourtextview.setText(hideText);
    // don't forget this ! or this will not work !
    yourtextview.setMovementMethod(LinkMovementMethod.getInstance());

Надеюсь, это сильно поможет!

  • У меня такая же проблема.
  • @ Ответ Дано абсолютно правильный. Но это не работает для меня.
  • После этого я обнаружил проблему, которую я добавил ClickableSpan. Так что он изменит мой цвет на другой цвет (акцентный цвет)

Проблема


SpannableStringBuilder не изменит цвет и не изменит линию, если вы добавите ClickableSpan после ForegroundColorSpan или UnderlineSpan.

Решение


1. С ClickableSpan

  • Вы можете переопределить метод updateDrawState внутри ClickableSpan .
  • В методе updateDrawState вы должны удалить обратный вызов super.
  • После этого вы должны изменить краску текста по мере необходимости.

2. Без ClickableSpan

  • Добавьте ForegroundColorSpan, чтобы изменить цвет текста.
  • Добавьте UnderlineSpan, чтобы добавить подчеркивание в текст.

Из документации разработчика, чтобы изменить цвет и размер spannable:

1- создать класс:

    class RelativeSizeColorSpan(size: Float,@ColorInt private val color: Int): RelativeSizeSpan(size) {

    override fun updateDrawState(textPaint: TextPaint?) {
        super.updateDrawState(textPaint)
        textPaint?.color = color
    } 
}

2 Создайте свой spannable, используя этот класс:

    val spannable = SpannableStringBuilder(titleNames)
spannable.setSpan(
    RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
    titleNames.length - microbe.name.length, // start
    titleNames.length, // end
    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)

Вы можете использовать функцию расширения в Kotlin

      fun CharSequence.colorizeText(
    textPartToColorize: CharSequence,
    @ColorInt color: Int
): CharSequence = SpannableString(this).apply {
    val startIndexOfText = this.indexOf(textPartToColorize.toString())
    setSpan(ForegroundColorSpan(color), startIndexOfText, startIndexOfText.plus(textPartToColorize.length), 0)
}

Использование:

      val colorizedText = "this text will be colorized"
val myTextToColorize = "some text, $colorizedText continue normal text".colorizeText(colorizedText,ContextCompat.getColor(context, R.color.someColor))
viewBinding.myTextView.text = myTextToColorize

Ниже отлично работает для меня

    tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
    String originalText = (String)tvPrivacyPolicy.getText();
    int startPosition = 15;
    int endPosition = 31;

    SpannableString spannableStr = new SpannableString(originalText);
    UnderlineSpan underlineSpan = new UnderlineSpan();
    spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
    spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    StyleSpan styleSpanItalic  = new StyleSpan(Typeface.BOLD);

    spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    tvPrivacyPolicy.setText(spannableStr);

Вывод для вышеуказанного кода

  1. создать текстовое представление в вашем макете
  2. вставьте этот код в ваш MainActivity

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
    

Теперь вы можете использовать библиотеку CodeView, чтобы легко выделять шаблоны разными цветами, например, чтобы выделить все URL-адреса внутри текста синим цветом, который вам просто нужно написать

      CodeView codeView = findViewById(R.id.codeview);
codeView.addSyntaxPattern(Patterns.WEB_URL, Color.BLUE);
codeView.setTextHighlighted(text);

URL репозитория CodeView: https://github.com/amrdeveloper/codeview

      First Part **Second Part should be Bold** last Part

Этот текст следует изменить с помощью SpannableString.

      import android.graphics.Typeface.BOLD
import android.text.Spannable
import android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan

val firstPart = "First Part  "
val secondPart = "Second Part should be Bold"
val thirdPart = "  last Part"
val finalString = firstPart + secondPart + thirdPart

val sb: Spannable = SpannableString(finalString).also {
                // ... Change text Colour
                it.setSpan(
                    ForegroundColorSpan(getColor(requireContext(), R.color.pink)),
                    finalString.indexOf(secondPart),
                    finalString.indexOf(secondPart) + secondPart.length,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
                // ... Make the text Bold
                it.setSpan(
                    StyleSpan(BOLD),
                    finalString.indexOf(secondPart),
                    finalString.indexOf(secondPart) + secondPart.length,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
                // ... Change Background Colour
                it.setSpan(
                    BackgroundColorSpan(getColor(requireContext(), R.color.lightPink)),
                    finalString.indexOf(secondPart) - 1,
                    finalString.indexOf(secondPart) + secondPart.length + 1,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
}

yourTextView.text = sb
Другие вопросы по тегам