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

(источник: twimg .com)
Можно ли установить цвет только диапазона текста в TextView?
Я хотел бы сделать что-то похожее на приложение Twitter, в котором часть текста выделена синим цветом. См. изображение ниже:

(источник: twimg .com)
Другой ответ был бы очень похож, но не нужно было бы дважды устанавливать текст 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 String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
Установите текст в TextView/Button/EditText и т. д., вызвав следующий код:
Просмотр текста:
TextView txtView = (TextView)findViewById(R.id.txtView);
Получить цветную строку:
String name = getColoredSpanned("Hiren", "#800000");
Установить текст в TextView:
txtView.setText(Html.fromHtml(name));
Готово
Есть фабрика для создания Spannable и избегайте приведения, например:
Spannable span = Spannable.Factory.getInstance().newSpannable("text");
Вот функция расширения 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)
Просто чтобы добавить к принятому ответу, так как все ответы говорят о 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);
Где я это нашел:
String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));
private SpannableString spannableString(String text, int start, int end) {
SpannableString spannableString = new SpannableString(text);
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;
}
Вывод:
Используя kotlin-ktx, вы легко добьетесь этого.
bindView?.oneTimePasswordTitle?.text = buildSpannedString {
append("One Time Password ")
inSpans(
ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
){
append(" (As Registered Email)")
}
}
вставьте этот код в 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
Некоторые ответы здесь не актуальны. Потому что вы (в большинстве случаев) добавите пользовательское действие при нажатии на ссылку.
Кроме того, как указано в справке по документации, цвет вашей ссылки на составную строку будет иметь цвет по умолчанию. "Цветом ссылки по умолчанию является цвет акцента темы или 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());
Надеюсь, это сильно поможет!
Из документации разработчика, чтобы изменить цвет и размер 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
)
Ниже работает отлично для меня
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);
Вывод для приведенного выше кода