Android开发中,SpannableString的setSpan(Object what,int start,int end,int flags)函数
what对象不能复用,一个对象重复使用就会失效掉上一个的赋值。例如下例,会导致第2行的setSpan失效:
1.ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(mContext.getResources().getColor(R.color.dark_textview));
2.spannableString.setSpan(foregroundColorSpan1,0,ARROW_LEFT_STR_INDEX,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
3.spannableString.setSpan(foregroundColorSpan1,ARROW_LEFT_STR_INDEX +currentIndexStr.length(),spannableString.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
解决方法:
1.使用临时变量
spannableString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.dark_textview)),0,ARROW_LEFT_STR_INDEX,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.minor_textview)),ARROW_LEFT_STR_INDEX +currentIndexStr.length(),spannableString.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.dark_textview)),spannableString.length() -ARROW_RIGHT_STR_INDEX,spannableString.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
2.重复定义局部变量:
ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(mContext.getResources().getColor(R.color.dark_textview));
ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(mContext.getResources().getColor(R.color.minor_textview))
ForegroundColorSpan foregroundColorSpan3 = new ForegroundColorSpan(mContext.getResources().getColor(R.color.dark_textview))
spannableString.setSpan(foregroundColorSpan1,0,ARROW_LEFT_STR_INDEX,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
spannableString.setSpan(foregroundColorSpan2,ARROW_LEFT_STR_INDEX +currentIndexStr.length(),spannableString.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
spannableString.setSpan(foregroundColorSpan3,spannableString.length() -ARROW_RIGHT_STR_INDEX,spannableString.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);