TextView设置部分文字为不同颜色等效果

有时候,我们需要设置同一个字符串中不同的颜色,可能需要用到下面的例子代码:

		String str = "美女们我爱你";
		String str1 = "美女们";
		if (!TextUtils.isEmpty(str)) {
			SpannableStringBuilder builder = new SpannableStringBuilder(str);
			// ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色
			ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.Red);
			ForegroundColorSpan blackSpan = new ForegroundColorSpan(Color.Black);
			builder.setSpan(redSpan, 0, str1.length(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			builder.setSpan(blackSpan, str1.length(), str.length(),
					Spannable.SPAN_INCLUSIVE_INCLUSIVE);
			TV.setText(builder);
		}




你可能感兴趣的:(android,textview)