Установить цвет TextView span в Android



можно ли установить цвет только промежуток текста в TextView?



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



679   11  

11 ответов:

другой ответ был бы очень похож, но не нужно, чтобы установить текст 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);
}

Если вы хотите больше контроля, вы можете проверить 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);
    }
};

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

Цвет Фона

enter image description here

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

Цвет

enter image description here

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

сочетание

enter image description here

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

Дальнейшего Изучения

задание TextView s текст spannable и определить 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);

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

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

Установить Цвет on текст by передав строку и цвета:

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

Набор текста on TextView / Button / EditText etc путем вызывать под кодом:

TextView:

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

Получить Цветные Строки:

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

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

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

сделал

  1. создать textview в UR layout
  2. вставьте этот код в ur 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
    
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);

выход:

enter image description here

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

рассмотрим, например, материал дизайн цвета определена в 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);

где я нашел что:

Comments

    Ничего не найдено.