我尝试使用此代码创建一个带有字符串“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应为纯白色,b d应为蓝色。
我做错了什么?
答案 0 :(得分: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);
答案 1 :(得分:0)
如果将Span设置为字母C和E,那么它在该点看起来是否正确?我觉得字母B上的setSpan正在覆盖剩余字符的'default'。那是我在黑暗中的镜头。