2

我尝试使用此代码创建一个带有字符串“abcde”的TextView,其中“b”和“d”跨越:

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

结果不是我想要的。a、c 和 e 应为纯白色,bd 应为蓝色。

我究竟做错了什么?

结果字符串,“a”为纯白色,“bdce”为蓝色

4

2 回答 2

1

尝试这个:

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);
于 2013-06-27T23:01:53.727 回答
0

如果将Span 设置为字母C 和E,那么此时它看起来是否正确?我有一种感觉,字母 B 上的 setSpan 正在覆盖其余字符的“默认值”。那是我在黑暗中拍摄的。

于 2012-08-27T21:18:11.263 回答