androidbackgroundtextviewandroid-spannable

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


What I'm actually doing is I'm storing a SpannableString in the form of HTML but it has a BackgroundColorSpan which has an aplha channel in its color. Now I got to know (via trials) that my aplha channel of the color goes away (due to inability of HTML) from the text whenever I try to store it.

Now what I want to know is that is there a way I can extract all the BackgroundColorSpan instances in the SpannableString AND change their color property? All the BackgroundColorSpan instances are of same color I just want to add an alpha channel to their color (by changing their color) before I present the text to users.

I figured out a way to extract all the BackgroundColorSpan instances by using getSpans but i still can't find a way to change their color.

Here's the related code:

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 item's color
    }
}

desc.setText(spannableDescString);

Solution

  • 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.