今日看到一本书上写了关于如何同时为TextView设置文字颜色和背景颜色的方案,随手试验了一把,表示效果不错。事例如下
package com.example.zhouxueli.myapplication;
import android.text.TextPaint;
import android.text.style.CharacterStyle;
public class ColorSpan extends CharacterStyle {
private int mTextColor;
private int mBackgroundColor;
public ColorSpan(int mTextColor, int mBackgroundColor) {
this.mTextColor = mTextColor;
this.mBackgroundColor = mBackgroundColor;
}
//该方法会在系统开始绘制需要设置样式的字符串之前被调用,以便绘制要修改文字的属性
@Override
public void updateDrawState(TextPaint tp) {
tp.bgColor=mBackgroundColor;
tp.setColor(mTextColor);
}
}
如下我是直接放在测试Activity 的onCreate()方法中的,其中使用到的textView只是我简单省事,直接在Activity的布局页面xml文件中放置了一个只有宽高属性的textView.
TextView textView=findViewById(R.id.tvSelf);
String text="<没有背景><黄色背景>\n\n<蓝色背景,红色文字>";
SpannableString spannableString=new SpannableString(text);
int start = 6;
int end = 12;
BackgroundColorSpan backgroundColorSpan=new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(backgroundColorSpan,start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = 14;
ColorSpan colorSpan = new ColorSpan(Color.RED,Color.BLUE);
spannableString.setSpan(colorSpan,start,text.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
展示效果如下截图示例