Set Color of Textview Span in Android

Set color of TextView span in Android

Another answer would be very similar, but wouldn't need to set the text of the TextView twice

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

How can I change the color of a part of a TextView?

Spannable is more flexible:

String text2 = text + CepVizyon.getPhoneCode() + "\n\n"
+ getText(R.string.currentversion) + CepVizyon.getLicenseText();

Spannable spannable = new SpannableString(text2);

spannable.setSpan(new ForegroundColorSpan(Color.WHITE), text.length(), (text + CepVizyon.getPhoneCode()).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

myTextView.setText(spannable, TextView.BufferType.SPANNABLE);

Changing Color Of TextView text in android using spannableString

Try like this

String text = TextUtils.join(" | ", Arrays.asList(new String[]{"1 Friend", "1 Review", "1 Coupons"}));

Spannable spannable = new SpannableString(text);

int index = text.indexOf('|');
while (index >= 0) {
spannable.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index = text.indexOf('|', index + 1);
}
detailsText.setText(hashText);

OutPut:

Sample Image

How to set different color to some text of a textiew and make that text clickable?

Using setHighlightColor() method works most of the time:

textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));

NOTE: Updated code to 2 different strings into 1 TextView and Second string will be coloured and clickable.

Set your TextView's default color as BLACK
Clickable part of will be GREEN

There is a simple example:

String stringFirst = "..."
String stringSecond = "..."

SpannableString spannable = new SpannableString(stringFirst + stringSecond);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
}

@Override
public void onClick(View widget) {
//Do your click action
}
};
spannable.setSpan(clickableSpan, stringFirst.length()-1, stringFirst.length() + stringSecond.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));

If it's not work add the line below

ds.setColor(ContextCompat.getColor(context, R.color.green));

to your updateDrawState method. It looks like this:

String stringFirst = "..."
String stringSecond = "..."

SpannableString spannable = new SpannableString(stringFirst + stringSecond);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(ContextCompat.getColor(context, R.color.green));
}

@Override
public void onClick(View widget) {
//Do your click action
}
};
spannable.setSpan(clickableSpan, stringFirst.length()-1, stringFirst.length() + stringSecond.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(ContextCompat.getColor(context, R.color.green));

change string color programmatically depending if condition

Try this code..

    textView = findViewById(R.id.tvData);
String mColoredString = "BLACK RED GREEN YELLOW ORANGE BLUE WHITE";
SpannableStringBuilder builder = new SpannableStringBuilder();

String strArray[] = mColoredString.split(" ");
for (int i = 0; i < strArray.length; i++) {
if (strArray[i].equals("RED")) {
SpannableString redSpannable = new SpannableString(strArray[i]);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, strArray[i].length(), 0);
builder.append(redSpannable);
} else if (strArray[i].equals("YELLOW")) {
SpannableString whiteSpannable = new SpannableString(strArray[i]);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, strArray[i].length(), 0);
builder.append(whiteSpannable);
} else if (strArray[i].equals("BLUE")) {
SpannableString blueSpannable = new SpannableString(strArray[i]);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, strArray[i].length(), 0);
builder.append(blueSpannable);
} else {
builder.append(strArray[i]);
}

}
textView.setText(builder);

}

Android: Coloring part of a string using TextView.setText()?

Use spans.

Example:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");

// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158));

// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);

// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

yourTextView.setText(sb);

Change the text color of a single ClickableSpan when pressed without affecting other ClickableSpans in the same TextView

I finally found a solution that does everything I wanted. It is based on this answer.

This is my modified LinkMovementMethod that marks a span as pressed on the start of a touch event (MotionEvent.ACTION_DOWN) and unmarks it when the touch ends or when the touch location moves out of the span.

public class LinkTouchMovementMethod extends LinkMovementMethod {
private TouchableSpan mPressedSpan;

@Override
public boolean onTouchEvent(TextView textView, Spannable spannable, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mPressedSpan = getPressedSpan(textView, spannable, event);
if (mPressedSpan != null) {
mPressedSpan.setPressed(true);
Selection.setSelection(spannable, spannable.getSpanStart(mPressedSpan),
spannable.getSpanEnd(mPressedSpan));
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
TouchableSpan touchedSpan = getPressedSpan(textView, spannable, event);
if (mPressedSpan != null && touchedSpan != mPressedSpan) {
mPressedSpan.setPressed(false);
mPressedSpan = null;
Selection.removeSelection(spannable);
}
} else {
if (mPressedSpan != null) {
mPressedSpan.setPressed(false);
super.onTouchEvent(textView, spannable, event);
}
mPressedSpan = null;
Selection.removeSelection(spannable);
}
return true;
}

private TouchableSpan getPressedSpan(
TextView textView,
Spannable spannable,
MotionEvent event) {

int x = (int) event.getX() - textView.getTotalPaddingLeft() + textView.getScrollX();
int y = (int) event.getY() - textView.getTotalPaddingTop() + textView.getScrollY();

Layout layout = textView.getLayout();
int position = layout.getOffsetForHorizontal(layout.getLineForVertical(y), x);

TouchableSpan[] link = spannable.getSpans(position, position, TouchableSpan.class);
TouchableSpan touchedSpan = null;
if (link.length > 0 && positionWithinTag(position, spannable, link[0])) {
touchedSpan = link[0];
}

return touchedSpan;
}

private boolean positionWithinTag(int position, Spannable spannable, Object tag) {
return position >= spannable.getSpanStart(tag) && position <= spannable.getSpanEnd(tag);
}
}

This needs to be applied to the TextView like so:

    yourTextView.setMovementMethod(new LinkTouchMovementMethod());

And this is the modified ClickableSpan that edits the draw state based on the pressed state set by the LinkTouchMovementMethod: (it also removes the underline from the links)

public abstract class TouchableSpan extends ClickableSpan {
private boolean mIsPressed;
private int mPressedBackgroundColor;
private int mNormalTextColor;
private int mPressedTextColor;

public TouchableSpan(int normalTextColor, int pressedTextColor, int pressedBackgroundColor) {
mNormalTextColor = normalTextColor;
mPressedTextColor = pressedTextColor;
mPressedBackgroundColor = pressedBackgroundColor;
}

public void setPressed(boolean isSelected) {
mIsPressed = isSelected;
}

@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(mIsPressed ? mPressedTextColor : mNormalTextColor);
ds.bgColor = mIsPressed ? mPressedBackgroundColor : 0xffeeeeee;
ds.setUnderlineText(false);
}
}

Most efficient way for Dynamic Text Color Change in TextView

Solution for span movement without calling setText method:

    final TextView tv = new TextView(this);
tv.setTextSize(32);
setContentView(tv);

SpannableStringBuilder ssb = new SpannableStringBuilder("0123456789012345678901234567890123456789");
ssb.append(ssb).append(ssb);
tv.setText(ssb, BufferType.SPANNABLE);
final Spannable sp = (Spannable) tv.getText();
final ForegroundColorSpan span = new ForegroundColorSpan(0xffff0000);
Runnable action = new Runnable() {
@Override
public void run() {
sp.setSpan(span, start, start + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start++;
if (start <= sp.length() - 4) {
tv.postDelayed(this, 50);
}
}
};
tv.postDelayed(action, 1000);

Solution for dynamic color change:

class HSVSpan extends CharacterStyle {
int color;
float[] hsv = {0, 1, 1};

@Override
public void updateDrawState(TextPaint tp) {
tp.setColor(color);
}

public void update() {
hsv[0] += 5;
hsv[0] %= 360;
color = Color.HSVToColor(hsv);
// Log.d(TAG, "update " + Integer.toHexString(color));
}
}

and testing code:

    final TextView tv = new TextView(this);
setContentView(tv);
SpannableStringBuilder ssb = new SpannableStringBuilder("0123456789");
final HSVSpan span = new HSVSpan();
ssb.setSpan(span, 2, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(ssb);
tv.setTextSize(32);

Runnable action = new Runnable() {
@Override
public void run() {
span.update();
tv.invalidate();
tv.postDelayed(this, 50);
}
};
action.run();

Is there any way to change the color of an already applied BackgroundColorSpan in a SpannableString?

Nevermind, I got the answer here

All I had to do was to delete the current span and replace it with the BackgroundColorSpan of the color that I required. Here's the code snippet.

SpannableString spannableDescString = new SpannableString(trimTrailingWhitespace(Html.fromHtml(note.getDesc())));
BackgroundColorSpan[] highlightSpanArray = spannableDescString.getSpans(0,spannableDescString.length(),BackgroundColorSpan.class);

if(highlightSpanArray.length!=0){

for(BackgroundColorSpan item : highlightSpanArray){
//what should i put here to change every items color

// get the span range
int start = spannableDescString.getSpanStart(item);
int end = spannableDescString.getSpanEnd(item);

// remove the undesired span
spannableDescString.removeSpan(item);

// set the new span with desired color
spannableDescString.setSpan(new BackgroundColorSpan(Color.RED),start,end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}

desc.setText(spannableDescString);

I simply didn't know if I could find the starting and ending of individual spans.

change color some string of textview

Use spans.

Example:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");

// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158));

// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);

// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

yourTextView.setText(sb);


Related Topics



Leave a reply



Submit