Bamaco
Bamaco

Reputation: 590

How can I span multiple strings in a TextView?

I tried this code to create a TextView with the string "abcde" where 'b' and 'd' have spanning:

private void testStringSpanning(TextView tv)
{
    // blue
    ForegroundColorSpan fcs = new ForegroundColorSpan( Color.BLUE );

    SpannableString  a = new SpannableString( "a" );
    SpannableString  b = new SpannableString( "b" );    
    b.setSpan( fcs, 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE );
    SpannableString  c = new SpannableString( "c" );
    SpannableString  d = new SpannableString( "d" );    
    d.setSpan( fcs, 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE );
    SpannableString  e = new SpannableString( "e" );

    SpannableStringBuilder builder = new SpannableStringBuilder();
    builder.append(a);
    builder.append(b);
    builder.append(c);
    builder.append(d);
    builder.append(e);

    tv.setText( builder, BufferType.SPANNABLE);
}

The result is not as I want. a, c and e should be plain white and b d should be blue.

What am I doing wrong?

result string with 'a' in plain white and 'bdce' in blue

Upvotes: 2

Views: 2070

Answers (2)

Oscar Méndez
Oscar Méndez

Reputation: 1007

Try this:

ForegroundColorSpan fcs = new ForegroundColorSpan( Color.BLUE );

//your strings in case you have most than one
String str1 = new String("a");
String str2 = new String("b");
String str3 = new String("c");
String str4 = new String("d");

//or a single one str = new String ("abcd")

//set all to on a TV
TextView string =(TextView)findViewById(R.id.tvString);
string.setText( str1 + str2 + str3 + str4, TextView.BufferType.SPANNABLE );

//convert all string y a single SpannableString
SpannableString s = (SpannableString)string.getText();

//This variables hepl you counting large strings
int str1_lenght = str1.length();
int str2_lenght = srt2.length();
int str3_lenght = srt3.length();
int str4_lenght = srt4.length();

//setting color on an specific string
s.setSpan(fcs, str1_lenght, str1_lenght + str2_lenght, 0);
s.setSpan(fcs, str1_lenght + str2_lenght + str3_lenght, str1_lenght + str2_lenght + str3_lenght + str4_lenght, 0);

Upvotes: 1

user1541338
user1541338

Reputation: 29

If you setSpan to the letters C and E, does it look correct at that point? I have a feeling that the setSpan on letter B is overwriting the 'default' on the remaining characters. That's my shot in the dark.

Upvotes: 0

Related Questions